MyBatis 是一款优秀的持久层框架
它支持自定义 SQL、存储过程以及高级映射
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis
2013年11月迁移到Github
如何获得Mybatis?
maven仓库
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.4version>
dependency>
官方文档:https://mybatis.org/mybatis-3/zh/getting-started.html
Gtihub:https://github.com/mybatis/mybatis-3
数据持久化
Dao层,Server层,Controller层…
搭建环境–>导入Mybatis–>编写代码–>测试
搭建数据库
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(30) DEFAULT NULL,
PASSWORD VARCHAR(30)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO USER VALUES(NULL,'唐嫣','123156'),
(NULL,'陈乔恩','12345792'),
(NULL,'胡歌','45135471'),
(NULL,'霍建华','1231478');
新建项目
新建一个普通的maven项目
导入maven依赖
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.19version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.4version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
dependencies>
编写Mybatis核心配置文件
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis? useSSL=true&useUnicode=true&characterEncoding=UTF- 8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="****"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
configuration>
编写Mybatis工具类
// SqlSessionFactory --> SqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resources = "mybatis-config.xml"; // mybatis核心配置文件路径
InputStream is = Resources.getResourceAsStream(resources); // 读取 Mybatis核心配置文件
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 获取 SqlSessionFactory实例
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){ // 定义获取SqlSession的方法
return sqlSessionFactory.openSession();
}
}
实体类
public class User {
private Integer id;
private String name;
private String password;
public User() {
}
public User(Integer id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Mapper接口(Dao)
public interface UserMapper {
public List<User> getUserList();=
}
接口实现类由原来的UserDaoImpl转变为一个UserMapper.xml配置文件
<mapper namespace="cn.codewei.dao.UserMapper">
<select id="getUserList" resultType="cn.codewei.pojo.User">
select * from user
select>
mapper>
junit测试
public class UserMapperTest {
@Test
public void getUserListTest(){
// 通过我们写好的工具类获取SqlSession
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
// sqlSession.getMapper()方法获取UserMapper对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 调用UserMapper的方法 执行sql语句 接收返回值
List<User> userList = mapper.getUserList();
// 遍历userList
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close(); // 关闭sqlSession
}
}
}
可能遇到的问题:出现异常
org.apache.ibatis.binding.BindingException: Type interface cn.codewei.dao.UserMapper is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册Mapper
解决方法:在Mybatis核心配置文件mybatis-config.xml中添加配置如下
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
异常:java.lang.ExceptionInInitializerError The error my exist in UserMapper.xml
出现该异常的原因是:配置文件没有读取到,是因为maven的原因
解决方法:在pom.xml中添加配置,手动配置资源过滤
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
可能会遇到的其他问题
UserMapper.xml 中 select update delete insert 的标签属性
/**
* 查询所有用户信息
* @return
*/
public List<User> getUserList();
<select id="getUserList" resultType="cn.codewei.pojo.User">
select * from user
select>
@Test
public void getUserListTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();;
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
}
}
在获取参数时,使用#{}来获取
{}中可以填写对象的属性名或者集合的key或传递的参数的变量名
/**
* 添加用户
* @param user
* @return
*/
public int insertUser(User user);
<insert id="insertUser" parameterType="cn.codewei.pojo.User">
insert into user(id,name ,password) values (#{id},#{name},#{password})
insert>
@Test
public void insertUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.insertUser(new User(5,"林心如","shw123zxc"));
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
/**
* 修改用户信息
* @param user
*/
public void updateUser (User user);
<update id="updateUser" parameterType="cn.codewei.pojo.User">
update user set name=#{name},password=#{password} where id=#{id}
update>
@Test
public void updateUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(2,"杨超越","shw112396"));
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
/**
* 根据用户的id 删除用户
* @param id
*/
public void deleteUser(int id);
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
delete>
@Test
public void deleteUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(3);
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map,不是很正规!但是很万能!!
/**
* 通过map传值,添加用户
* @param map
*/
public void addUser(Map map);
<insert id="addUser" parameterType="Map">
insert into user(id,name,password) values (#{Id},#{NaMe},#{PassWord})
insert>
/**
* 通过map传参,增加用户
*/
@Test
public void addUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("Id",6);
map.put("NaMe","刘诗诗");
map.put("PassWord","1234897");
mapper.addUser(map);
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
Map传参数,直接在sql中取出key即可! 【parameterType=“Map”】
对象传递参数,直接在sql中取出对象的属性即可! 【parameterType=“Object”】
如:【parameterType=“cn.codewei.pojo.UserMapper”】
只有一个基本类型参数的情况下,可以直接在sql中取到!
如:【parameterType=“int”】 也可以什么都不写
多个参数用Map,或者注解!
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
databaseldProvider(数据库厂商标识)
mappers(映射器)
Mybatis可以适应多种环境
尽管可以配置多个环境,但每个SqlSessionFactory实例只能选着一种环境
我们可以通过properties来实现引用配置文件
这些属性都是可以外部配置且动态替换的,既可以在典型的java属性文件中配置,也可以通过properties元素的子元素来传递
如:
编写一个配置文件db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=xxxxxx
在核心配置文件mybatis-config.xml中引入
注意:要写在标签内的最上方
<configuration>
<properties resource="db.properties" />
<typeAliases>
<typeAlias type="cn.codewei.pojo.User" alias="User" />
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="cn/codewei/dao/UserMapper.xml"/>
mappers>
configuration>
注意:在==…==中可以额外添加一些属性,如:
<properties resource="db.properties">
<property name="xxx" value="xxx" />
<property name="xxx" value="xxx" />
properties>
这样定义的属性,也可以在环境中"${xxx}"读取到
当外部配置文件中的属性和在标签中定义的属性有重复时,优先使用外部配置文件中配置的属性
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。例如:
<typeAliases>
<typeAlias alias="Author" type="cn.codewei.pojo.Author"/>
<typeAlias alias="Blog" type="cn.codewei.pojo.Blog"/>
<typeAlias alias="Comment" type="cn.codewei.pojo.Comment"/>
<typeAlias alias="Post" type="cn.codewei.pojo.Post"/>
<typeAlias alias="Section" type="cn.codewei.pojo.Section"/>
<typeAlias alias="User" type="cn.codewei.pojo.User"/>
typeAliases>
这样定义了别名后,就可以在Mapper配置文件中使用别名了,就不用写全类名了,如
<select id="getUserList" resultType="User">
select * from user
select>
另一种方法,可以指定一个包名,mybatis会在包名下面搜索需要的JavaBean,如
<typeAliases>
<package name="cn.codewei.pojo"/>
typeAliases>
每一个在包cn.codewei.pojo中的JavaBean,在没有注解的情况下,会使用Bean的首字母小写的非限定类名来作为它的别名,也就是,它的默认别名为这个类的类名首字母的小写形式
在实体类较少的时候,一般使用第一种方式,可以自定义别名
如果实体类十分多,建议使用第二种方式,如果想要值定义别名,则要在实体类上添加注解@Alias(“自定义注解”),如:
@Alias("hello")
public void UserMapper(){
private int id;
privat String name;
...
}
下面是一些为常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。
别名 | 映射的类型 |
---|---|
_byte | byte |
_long | long |
_short | short |
_int | int |
_integer | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
integer | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
bigdecimal | BigDecimal |
object | Object |
map | Map |
hashmap | HashMap |
list | List |
arraylist | ArrayList |
collection | Collection |
iterator | Iterator |
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true | false | true |
lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 |
true | false | false |
mapUnderscoreToCamelCase | 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 | true | false | False |
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置… |
… | … | … | … |
注册绑定Mapper文件
方式一:(推荐使用)
<mappers>
<mapper resource="cn/codewei/dao/AuthorMapper.xml"/>
<mapper resource="cn/codewei/dao/UserMapper.xml"/>
<mapper resource="cn/codewei/builder/PostMapper.xml"/>
mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="cn.codewei.dao.AuthorMapper"/>
<mapper class="cn.codewei.dao.UserMapper"/>
<mapper class="cn.codewei.builder.PostMapper"/>
mappers>
==注意:==1. 接口和其对应的Mapper配置文件必须同名
2. 接口和其对应的Mapper配置文件必须在同一包下
方式三:使用扫描包注册绑定
<mappers>
<package name="cn.codewei.dao"/>
mappers>
==注意:==1. 接口和其对应的Mapper配置文件必须同名
2. 接口和其对应的Mapper配置文件必须在同一包下
不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder
一旦创建了SqlSessionFactory,就不再需要SqlSessionFactoryBuilder了
局部变量
SqlSessionFactory
可以将其想象成数据库连接池
SqlSessionFactory一旦被创建就应该一直存在,没有理由丢弃它或重新创建另一个实例
因此,SqlSessionFactory的最佳作用域是应用作用域
最简单的就是使用单例模式或者静态单例模式
SqlSession
可以看成连接到连接池的一个请求
SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
用完之后需要立即关闭,否则资源被占用
每一个Mapper,代表一个具体的业务
Mapper中属性名和数据库中的字段名无法对应
如:
在数据库中字段为 id name password
在User实体类中为 id name pwd
<select id="getUserById" resultType="cn.codewei.pojo.User" parameterType="int">
select id,name,password from user where id = #{id}
select>
查询结果为:
这样,查询到的password就无法封装到User对象中,pwd就为null
解决方法:
起别名
<select id="getUserById" resultType="cn.codewei.pojo.User" parameterType="int">
select id,name,password as pwd from user where id = #{id}
select>
查询结果为:
一般不使用起别名的方法解决,通过resultMap结果集映射进行解决
<resultMap id="UserMap" type="User">
<result column="password" property="pwd" />
resultMap>
<select id="getUserById" resultMap="UserMap" parameterType="int">
select * from user where id = #{id}
select>
resultMap
元素是 MyBatis 中最重要最强大的元素ResultMap
的优秀之处——你完全可以不用显式地配置它们如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的选择!
在Mybatis中具体使用哪一个日志,在Mybatis的核心配置文件mybatis.xml中进行设置
1. STDOUT_LOGGING
标准日志输出,不需要任何配置
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
2. LOG4J
我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
使用步骤:
导入log4j的依赖jar包
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
新建一个配置文件,log4j.properties(配置文件内容从网上查询)
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/codewei.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
在Mybatis核心配置文件mybatis-config.xml中配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
log4j的使用
直接运行项目就可以看到日志文件的打印
简单使用
如果要在输出日志的类中加入相关语句
Logger logger = Logger.getLogger(当前类.class); // 获取日志对象
logger.info("info:进入了log4j!");
logger.debug("debug:进入了log4j!");
logger.error("error:进入了log4j!");
日志级别:
从高到底 ERROR–>WARN–>INFO–>DEBUG
如果定义了INFO级别,则DEBUG级别的日志信息将不会被打印,只会打印高于INFO级别(如,INFO,WARN,ERROR)的日志信息
##语法:
SELECT * from user limit startIndex,endIndex;
SELECT * from user limit 3; ##[0,2]
使用Mybatis分页,核心SQL
接口
public List<User> getUserByLimit(Map<String,Object> map);
Mapper.xml
<resultMap id="UserMap" type="User">
<result column="password" property="pwd" />
resultMap>
<select id="getUserByLimit" resultMap="UserMap" parameterType="map">
select * from user limit #{start},#{end}
select>
测试
@Test
public void getUserByLimitTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("start",0);
map.put("end",2);
List<User> list = mapper.getUserByLimit(map);
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
了解,开发中不建议使用
不再使用sql实现分页,使用java实现分页
接口
public List<User> getUserByRowBounds();
Mapper.xml
<resultMap id="UserMap" type="User">
<result column="password" property="pwd" />
resultMap>
<select id="getUserByRowBounds" resultMap="UserMap">
select * from user
select>
测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
List<Object> list = sqlSession.selectList("cn.codewei.mybatis04.dao.UserMapper.getUserByRowBounds", null, new RowBounds(0, 2));
for (Object o : list) {
System.out.println(o);
}
sqlSession.close();
}
Mybatis一般还是使用xml进行配置开发
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范更好
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了
而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离
接口的本身反映了系统设计人员对系统的抽象理解
接口应有两类:
一个体有可能有多个抽象面
抽象体与抽象面是有区别的
三个面向区别
面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题
@Select("select * from user")
public List<User> getUserList();
<mappers>
<mapper class="cn.codewei.dao.UserMapper" />
mappers>
本质:反射机制
底层:动态代理
在有多个参数时,要使用注解@Param
@Select("select * from user where name=#{name} and gender=#{gender}")
public void getUser(@Param("name") String name ,@Param("gender") String gender);
使用步骤:
在项目中导入lombok的jar包
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
在实体类上加注解
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
Lombok config system
常用:
@Getter 所有getter方法
@Setter 所有setter方法
@ToString toString
@EqualsAndHashCode equals,hashcode
@AllArgsConstructor 满参构造
@NoArgsConstructor 空参构造
@Data 无参构造,getter,setter,toString,hashcode,equals
多对一:
如图:
多个学生,对应一个老师
对于学生,多个学生关联一个老师【多对一】
对于老师,一个老师集合多个学生【一对多】
SQL:
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
导入Lombok
新建实体类 Teacher,Student
// Teacher实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private Integer id;
private String name;
}
// Student实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Integer id;
private String name;
// 学生需要关联一个老师
private Teacher teacher;
}
建立Mapper接口
建立Mapper.xml文件
在核心配置文件中绑定注册Mapper接口或者文件
测试查询是否能够成功
<select id="getStudent" resultMap="StudentTeacher">
select * from student
select>
<resultMap id="StudentTeacher" type="Student">
<result column="id" property="id" />
<result column="name" property="name" />
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher">association>
resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
select>
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.id tid,t.name tname from student s inner join teacher t on s.tid = t.id
select>
<resultMap id="StudentTeacher2" type="Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
<association property="teacher" javaType="Teacher">
<result column="tid" property="id"/>
<result column="tname" property="name"/>
association>
resultMap>
将查询出来的结果,一一映射,对于Student的属性teacher,其类型为Teacher,再将查询到的Teacher的数据映射到Teacher对应的属性
比如:一个老师拥有多个学生
对于老师,就是一对多的关系
导入Lombok
新建实体类 Teacher,Student
// Teacher实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private Integer id;
private String name;
// 一个老师拥有多个学生
private List<Student> students;
}
// Student实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Integer id;
private String name;
private int tid;
}
建立Mapper接口
建立Mapper.xml文件
在核心配置文件中绑定注册Mapper接口或者文件
测试查询是否能够成功
<select id="getTeacher2" parameterType="int" resultMap="TeacherStudent2">
select * from teacher where id=#{id}
select>
<resultMap id="TeacherStudent2" type="cn.codewei.pojo.Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" column="id" javaType="ArrayList" ofType="cn.codewei.pojo.Student" select="getStudentByTeacherId">collection>
resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid=#{id}
select>
<select id="getTeacher" parameterType="int" resultMap="TeacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname from teacher t
inner join student s on t.id=s.tid where t.id=#{id}
select>
<resultMap id="TeacherStudent" type="cn.codewei.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="cn.codewei.pojo.Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
collection>
resultMap>
对通过多表查询获取到的Student的信息进行映射,返回值是List集合,List集合的泛型是Student,通过ofType可以获取到集合的泛型,从而对Student的属性进行映射
动态SQL指根据不同的条件生成不同的SQL语句
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
if
choose (when, otherwise)
trim (where, set)
foreach
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建一个基础工程
导包
编写配置文件
<configuration>
<properties resource="db.properties" />
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
<typeAliases>
<typeAlias type="cn.codewei.pojo.blog" alias="blog"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
mappers>
configuration>
编写实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class blog {
private String id;
private String title;
private String author;
private Date createTime;
private Integer views;
}
编写对应的Mapper接口和Mapper.xml文件
package cn.codewei.dao;
public interface BlogMapper {
}
<mapper namespace="cn.codewei.dao.BlogMapper">
mapper>
在核心配置文件中绑定Mapper.xml文件
<select id="queryBolgIF" resultType="Blog" parameterType="map">
select * from blog where 1=1
<if test="title!=null">
and title=#{title}
if>
<if test="author!=null">
and author=#{author}
if>
select>
@Test
public void queryBolgIFTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("title","Java如此简单");
List<Blog> blogs = mapper.queryBolgIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除
第一个语句不需要加and或or
后面的语句都要加and或者or
如上述13.2中if语句中sql代码通过where改造:
<select id="queryBolgIF" resultType="Blog" parameterType="map">
select * from blog
<where>
<if test="title!=null">
title=#{title}
if>
<if test="author!=null">
and author=#{author}
if>
where>
select>
<select id="queryBolgChoose" resultType="Blog" parameterType="map">
select * from blog
<where>
<choose>
<when test="title!=null">
title =#{title}
when>
<when test="author!=null">
and author=#{author}
when>
<otherwise>
and views=9999
otherwise>
choose>
where>
select>
如果执行第一个when这后面when标签和otherwise标签内的内容都不会被执行
用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列
<update id="updateBlog" parameterType="map" >
update blog
<set>
<if test="title!=null">
title=#{title},
if>
<if test="author!=null">
author=#{author}
if>
set>
where id = #{id}
update>
不用手动写set,set便签中最后一个语句不用加逗号,其他语句需要加
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)
where 和 set 标签的本质就是trim标签
如,where标签可以替换为
<trim prefix="WHERE" prefixOverridex="AND|OR">
...
trim>
如,set标签可以替换为
<trim prefix="SET" suffixOverrides=",">
...
trim>
prefix:前缀
prefixOverridex:前缀覆盖
suffix:后缀
suffixOverridex:后缀覆盖
通过trim标签,我们可以自定义一些自己想要的功能
所谓动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
有点时候,我们可能会将一些公共的部分抽取出来,方便复用
<sql id="if-title-author">
<if test="title!=null">
title=#{title}
if>
<if test="author!=null">
and author=#{author}
if>
sql>
<select id="queryBolgIF" resultType="Blog" parameterType="map">
select * from blog
<where>
<include refid="if-title-author">include>
where>
select>
注意:
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
如:
select * from user where 1=1 and
<foreach item="id" collection="ids" open="(" separator="or" close=")">
#{id}
foreach>
(id=1 or id=2 or id=3)
案例:查询ID为1,2,3号记录的博客
// BlogMapper
//查询第1,2,3号记录的博客
List<Blog> queryBlogForeach(Map map);
// BlogMapper.xml
<select id="queryBlogForeach" resultType="Blog" parameterType="map">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
foreach>
where>
select>
// 测试
@Test
public void queryBlogForeachTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
List<Integer> ids = new ArrayList<Integer>();
Collections.addAll(ids,1,2,3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
通过foreach标签,拼接出来的sql为:
select * from blog WHERE ( id=1 or id=2 or id=3 )
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:先在Mysql中写出完整的SQL,再对应的修改成动态SQL,实现通用即可
测试步骤:
开启日志
测试在一个Session中查询两次相同记录
@Test
public void queryUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapperr mapper = sqlSession.getMapper(UserMapperr.class);
User user = mapper.queryUser(2);
System.out.println(user);
System.out.println("=====================");
User user1 = mapper.queryUser(2);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}
查看日志输出
在实行了增删改后会清空缓存,再次查询数据库
手动清空缓存:sqlSession.clearCache();
一级缓存是默认开启的,只在一次sqlSession中有效
二级缓存需要手动开启和配置,他是基于namespace级别的缓存
要启用全局的二级缓存,只要在SQL映射文件Mapper.xml中添加一行
<cache/>
如:
标签中可以定义一些属性:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的
步骤:
在Mybatis-config.xml中,开启全局缓存
<setting name="cacheEnabled" value="true"/>
在要使用二级缓存的Mapper.xml中开启二级缓存
<cache/>
我们需要将实体类序列化,否则就会报错
所有数据都会先放在一级缓存中,只有当会话提交或者关闭的时候,才会提交到二级缓存中
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider
在使用之前,先导包
<dependency>
<groupId>org.mybatis.cachesgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.1.0version>
dependency>
编写cache的type属性
<cache type="org.mybatis.caches.ehcache.EhBlockingCache"/>
编写一个配置文件,ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
ehcache>
现在,一般会使用Redis数据库来做缓存!