注:前两部分只是大概介绍
重点是第三部分的 MyBatis注解方式进行开发
一、MyBatis 中的延迟加载
1. 延迟加载
在真正使用数据时才发起查询,不用的时候不查询;按需加载(懒加载);
2. 立即加载
不管用不用,只要一调用方法,马上发起查询;
在对应的四种表关系中:
- 一对多、一对多:通常用 延迟加载;
- 多对一、一对一:通常用 立即加载;
二、MyBatis 中的缓存
1. 一级缓存
一级缓存是 SQLSession 范围的缓存,当调用 SQLSession 的修改、添加、删除、commit()、close() 等方法时,就会清空一级缓存;
2. 二级缓存
三、MyBatis 的注解开发
用注解方式进行开发,可替代原来的配置文件 IUserDao.xml;
1. 环境搭建
(1)创建新项目
(2)编辑 pom.xml 文件
这里直接给出整个项目的文件目录
pom.xml 文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MyBatisTest2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
(3)导入两个配置文件:
jdbcConfig.properties 和 log4j.properties
- jdbcConfig.properties 文件内容如下:
(该文件内容就是连接数据库用到的信息)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdata?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
- log4j.properties 内容如下:
log4j.rootLogger=INFO,CONSOLE
log4j.addivity.org.apache=true
# console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=UTF-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[demo] %-5p %d{yyyy-MM-dd HH\:mm\:ss} - %C.%M(%L)[%t] - %m%n
# all
log4j.logger.com.demo=INFO, DEMO
log4j.appender.DEMO=org.apache.log4j.RollingFileAppender
log4j.appender.DEMO.File=${catalina.base}/logs/demo.log
log4j.appender.DEMO.MaxFileSize=50MB
log4j.appender.DEMO.MaxBackupIndex=3
log4j.appender.DEMO.Encoding=UTF-8
log4j.appender.DEMO.layout=org.apache.log4j.PatternLayout
log4j.appender.DEMO.layout.ConversionPattern=[demo] %-5p %d{yyyy-MM-dd HH\:mm\:ss} - %C.%M(%L)[%t] - %m%n
(4)创建 SqlMapConfig.xml 文件
- SqlMapConfig.xml 内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部配置文件-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置别名-->
<typeAliases>
<package name="domain"></package>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--指定带有注解的dao接口所在位置-->
<mappers>
<package name="dao"></package>
</mappers>
</configuration>
2. 单表 CRUD 操作
(1)准备数据库
CREATE TABLE `user`(
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`),
)ENGINE=INNODB DEFAULT CHARSET=utf8;
(2)创建 User.java 类
(根据前面的目录,在适当位置创建即可)
- User.java 内容如下:
定义变量,以及相应的 get 和 set 方法,toString 方法;
package domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
(3)创建 IUserDao.java 接口
- IUserDao.java 内容如下:
package dao;
import domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
/**
* 在 mybatis 中针对 CRUD ,一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer userId);
/**
* 根据 Id 查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
//两种写法(AnnotationCRUDTest.java 中也要改写)
// @Select("select * from user where username like #{username}")
@Select("select * from user where username like '%${value}%'")
List<User> findUserByName(String username);
/**
* 查询用户数量
* @return
*/
@Select("select count(*) from user")
int findTotalUser();
}
(4)创建 测试类:AnnotationCRUDTest.java
- AnnotationCRUDTest.java 内容如下
import dao.IUserDao;
import domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class AnnotationCRUDTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IUserDao userDao;
@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
sqlSession = factory.openSession();
userDao = sqlSession.getMapper(IUserDao.class);
}
@After
public void destroy() throws Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
/**
* 查询所有
*/
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users){
//System.out.println("----------每个用户的信息----------");
System.out.println(user);
//System.out.println(user.getAccounts());
}
}
/**
* 保存用户
*/
@Test
public void testSave(){
User user = new User();
user.setUsername("zzz");
user.setAddress("北京");
userDao.saveUser(user);
}
/**
* 更新用户
*/
@Test
public void testUpdate(){
User user = new User();
user.setId(27);
user.setUsername("eee");
user.setAddress("上海");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
}
/**
* 删除用户
*/
@Test
public void testDelete(){
userDao.deleteUser(27);
}
/**
* 根据 Id 查询用户信息
*/
@Test
public void testFindOne(){
User user = userDao.findById(26);
System.out.println(user);
}
/**
* 根据用户名称模糊查询
*/
@Test
public void testFindByName(){
//两种写法(IUserDao.java 中也要改写)
// List<User> users = userDao.findUserByName("%c%");
List<User> users = userDao.findUserByName("c");
for (User user : users){
System.out.println(user);
}
}
/**
* 查询用户数量
*/
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
}
}
(5)测试结果
- 依次运行测试类中的每个测试方法
以 testFindAll() 方法为例:
3. 多表查询操作
(1)准备数据库
- 在之前数据库的基础上,创建一张 account 表
CREATE TABLE `account`(
`ID` int(11) NOT NULL COMMENT '编号',
`UID` int(11) DEFAULT NULL COMMENT '用户编号',
`MONEY` DOUBLE DEFAULT NULL COMMENT '金额',
PRIMARY KEY (`ID`),
KEY `FK_Reference_8` (`UID`),
CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
(2)创建 Account.java 类 & 修改 User.java 类
- Account.java 内容如下:
package domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//多对一(MyBatis 中称之为一对一)的映射:一个账户只能属于一个用户
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
-
User.java 给原来的文件中添加了如下内容:
-
修改后的 User.java 内容如下:
package domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//一对多关系映射,一个用户对应多个账户
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
(3)创建 IAccountDao.java 接口 & 修改 IUserDao.java 接口
- IAccountDao.java 内容如下:
package dao;
import domain.Account;
import domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IAccountDao {
/**
* 查询所有账户,并且获取每个账户所所属的用户信息
* @return
*/
@Select("select * from account")
@Results(id="accountMap",value = {
@Result(id = true, column = "id", property = "id"),
@Result(column = "uid", property = "uid"),
@Result(column = "money", property = "money"),
@Result(property = "user", column = "uid",
one = @One(select = "dao.IUserDao.findById",
fetchType = FetchType.EAGER))
})
List<Account> findAll();
/**
* 根据 用户Id 查询 账户信息
* @param
* @return
*/
@Select("select * from account where uid = #{userId}")
List<Account> findAccountByUid(Integer userId);
}
-
IUserDao.java 添加了如下内容:
-
修改后的 IUserDao.java 如下:
package dao;
import domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
/**
* 在 mybatis 中针对 CRUD ,一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id = "userMap", value = {
@Result(id = true, column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "address", property = "address"),
@Result(column = "sex", property = "sex"),
@Result(column = "birthday", property = "birthday"),
@Result(property = "accounts", column = "id",
many = @Many(select = "dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer userId);
/**
* 根据 Id 查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
//两种写法(AnnotationCRUDTest.java 中也要改写)
// @Select("select * from user where username like #{username}")
@Select("select * from user where username like '%${value}%'")
List<User> findUserByName(String username);
/**
* 查询用户数量
* @return
*/
@Select("select count(*) from user")
int findTotalUser();
}
(4)创建 测试类:AccountTest.java & 修改 测试类:AnnotationCRUDTest.java
- AccountTest.java 内容如下:
import dao.IAccountDao;
import dao.IUserDao;
import domain.Account;
import domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class AccountTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IAccountDao accountDao;
@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
sqlSession = factory.openSession();
accountDao = sqlSession.getMapper(IAccountDao.class);
}
@After
public void destroy() throws Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
/**
* 查询所有信息
*/
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
for (Account account : accounts){
System.out.println("-------每个账户的信息-------");
System.out.println(account);
System.out.println(account.getUser());
}
}
}
- AnnotationCRUDTest.java 内容如下:
import dao.IUserDao;
import domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class AnnotationCRUDTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IUserDao userDao;
@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
sqlSession = factory.openSession();
userDao = sqlSession.getMapper(IUserDao.class);
}
@After
public void destroy() throws Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
/**
* 查询所有
*/
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users){
System.out.println("----------每个用户的信息----------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
/**
* 保存用户
*/
@Test
public void testSave(){
User user = new User();
user.setUsername("zzz");
user.setAddress("北京");
userDao.saveUser(user);
}
/**
* 更新用户
*/
@Test
public void testUpdate(){
User user = new User();
user.setId(27);
user.setUsername("eee");
user.setAddress("上海");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
}
/**
* 删除用户
*/
@Test
public void testDelete(){
userDao.deleteUser(27);
}
/**
* 根据 Id 查询用户信息
*/
@Test
public void testFindOne(){
User user = userDao.findById(26);
System.out.println(user);
}
/**
* 根据用户名称模糊查询
*/
@Test
public void testFindByName(){
//两种写法(IUserDao.java 中也要改写)
// List<User> users = userDao.findUserByName("%c%");
List<User> users = userDao.findUserByName("c");
for (User user : users){
System.out.println(user);
}
}
/**
* 查询用户数量
*/
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
}
}
(5)测试结果
- 运行 AnnotationCRUDTest.java 文件 中的 testFindAll() 方法:
- 运行 AccountTest.java 中的 testFindAll() 方法:
4. 缓存的配置
(1)修改配置文件 SqlMapConfig.xml
-
增加如下内容:
-
修改后的文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部配置文件-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置二级缓存-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!--配置别名-->
<typeAliases>
<package name="domain"></package>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--指定带有注解的dao接口所在位置-->
<mappers>
<package name="dao"></package>
</mappers>
</configuration>
(2)修改 IUserDao.java 文件
- 添加内容及位置如下:
@CacheNamespace(blocking = true) //开启二级缓存
(3)添加 测试类:SecondLevelCatchTest.java
- SecondLevelCatchTest.java 内容如下:
import dao.IUserDao;
import domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class SecondLevelCatchTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IUserDao userDao;
@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
sqlSession = factory.openSession();
userDao = sqlSession.getMapper(IUserDao.class);
}
@After
public void destroy() throws Exception{
in.close();
}
/**
* 查询所有
*/
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users){
System.out.println("----------每个用户的信息----------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
/**
* 根据 Id 查询用户信息
*/
@Test
public void testFindOne(){
User user = userDao.findById(24);
System.out.println(user);
sqlSession.close(); //释放一级缓存
sqlSession = factory.openSession(); //再次打开session
IUserDao userDao1 = sqlSession.getMapper(IUserDao.class);
User user1 = userDao1.findById(24);
System.out.println(user1);
System.out.println(user == user1);
sqlSession.close();
}
}
(4)测试结果
- 运行 该测试类的 testFindAll() 方法:
备注