往期内容,如下
一、MyBatis简介
二、MyBatis环境搭建
三、MyBatis入门案例
四、MyBatis自定义
五、MyBatis CRUD操作
六、Mybatis中参数和返回值的深入了解
七、MyBatis 配置文件标签
八、MyBatis POOLED连接池深入了解
九、MyBatis中的动态sql语句
十、MyBatis多表查询操作
十一、Mybatis中的延迟加载和缓存
1.环境搭建
1.1 最终代码目录结构
1.2 数据库数据
DROP TABLE IF EXISTS `user`;
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;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'老王','2018-02-27 17:47:08','男','北京'),(42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'),(43,'小二王','2018-03-04 11:34:34','女','北京金燕龙'),(45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'),(46,'老王','2018-03-07 17:37:26','男','北京'),(48,'小马宝莉','2018-03-08 11:44:00','女','北京修正');
1.3 配置文件
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>com.itheima</groupId>
<artifactId>day04_eesy_03annotation_mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy_mybatis
jdbc.username=root
jdbc.password=1234
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
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="com.itheima.domain"></package>
</typeAliases>
<!-- 配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<!-- 指定带有注解的dao接口所在位置 -->
<mappers>
<package name="com.itheima.dao"></package>
</mappers>
</configuration>
1.4 实体类
com.itheima.domain.User
package com.itheima.domain;
import java.io.Serializable;
import java.util.Date;
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 +
'}';
}
}
1.5 接口
com.itheima.dao.IUserDao
package com.itheima.dao;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
List<User> findAll();
2.注解开发测试
在Mybatis中,针对CRUD一共有四个注解
@Select
@Insert
@Update
@Delete
修改com.itheima.dao.IUserDao
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
编写测试类
package com.itheima.test;
import com.itheima.dao.IUserDao;
import com.itheima.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 java.io.InputStream;
import java.util.List;
public class MybatisAnnoTest {
public static void main(String[] args) throws Exception {
/*
*测试基于注解的Mybatis使用
*/
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
List<User> users = userDao.findAll();
for (User user : users){
System.out.println(user);
}
session.close();
in.close();
}
}
运行测试方法,结果如下:
2.1 Mybatis中的细节
如果你的资源文件夹配置了Dao的配置文件IUserDao.xml
无论你在SqlMapConfig.xml
中配置的是<mapper class="com.itheima.dao.IUserDao"></mapper>
还是<package name="com.itheima.dao"></package>
都会报错
<mapper class="com.itheima.dao.IUserDao"></mapper>
:指定使用注解开发
<mapper resource=""com/itheima/dao/IUserDao.xml"></mapper>
:指定使用xml开发
<package name="com.itheima.dao"></package>
:Mybatis自己去判断是xml还是注解
3. 注解开发的CRUD操作
3.1 保存操作
在com.itheima.dao.IUserDao
添加新方法
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
新建测试类com.itheima.test.AnnotationCRUDTest
和测试方法testSave()
package com.itheima.test;
import com.itheima.dao.IUserDao;
import com.itheima.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 session;
private IUserDao userDao;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}
@After
public void destroy()throws Exception{
session.commit();
session.close();
in.close();
}
@Test
public void testSave(){
User user = new User();
user.setUsername("mybatis annotation");
user.setAddress("北京市昌平区");
userDao.saveUser(user);
}
}
运行testSave()
方法,结果如下
3.2 更新操作
在com.itheima.dao.IUserDao
添加新方法
/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);
在测试类com.itheima.test.AnnotationCRUDTest
添加测试方法testUpdate()
@Test
public void testUpdate(){
User user = new User();
user.setId(49);
user.setUsername("mybatis annotation update");
user.setAddress("北京市海淀区");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
}
执行testUpdate()
方法,结果如下
3.3 删除操作
在com.itheima.dao.IUserDao
添加新方法`
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id} ")
void deleteUser(Integer userId);
在测试类com.itheima.test.AnnotationCRUDTest
添加测试方法testDelete()
@Test
public void testDelete(){
userDao.deleteUser(49);
}
执行testDelete()
方法,结果如下
3.4 查询操作
3.4.1 根据用户id查询用户
在com.itheima.dao.IUserDao
添加新方法
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id} ")
User findById(Integer userId);
在测试类com.itheima.test.AnnotationCRUDTest
添加测试方法testFindOne()
@Test
public void testFindOne(){
User user = userDao.findById(48);
System.out.println(user);
}
执行testFindOne()
方法,结果如下
3.4.2 根据用户名称模糊查询
在com.itheima.dao.IUserDao
添加新方法
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
// @Select("select * from user where username like #{username} ")
@Select("select * from user where username like '%${value}%' ")
List<User> findUserByName(String username);
在测试类com.itheima.test.AnnotationCRUDTest
添加测试方法testFindByName()
@Test
public void testFindByName(){
// List<User> users = userDao.findUserByName("%mybatis%");
List<User> users = userDao.findUserByName("老王");
for(User user : users){
System.out.println(user);
}
}
执行testFindByName()
方法,结果如下:
3.4.3 查询总用户数量
在com.itheima.dao.IUserDao
添加新方法
/**
* 查询总用户数量
* @return
*/
@Select("select count(*) from user ")
int findTotalUser();
在测试类com.itheima.test.AnnotationCRUDTest
添加测试方法testFindTotal()
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
}
执行testFindTotal()
方法,结果如下
4. 使用注解配置实体类属性和数据库列名的对应关系(映射)
既然要配置映射,所以我们要把实体类属性名和数据库列名修改为不一致的
com.itheima.domain.User
package com.itheima.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public Date getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}
修改com.itheima.dao.IUserDao
的findAll
方法
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "address",property = "userAddress"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(property = "accounts",column = "id",
many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
执行com.itheima.test.AnnotationCRUDTest
的testFindAll
方法,结果如下
在@Resul
t注解中有一个属性id
,我们通过这个id
定义一个标识符,来标识映射,在别的方法上如果需要使用映射,那就再方法上使用注解@ResultMap("userMap")
com.itheima.dao.IUserDao
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id} ")
@ResultMap("userMap")
User findById(Integer userId);
执行com.itheima.test.AnnotationCRUDTest
中的方法testFindOne
@Test
public void testFindOne(){
User user = userDao.findById(48);
System.out.println(user);
}
结果如下
5. 注解开发的查询配置
5.1 一对一的查询配置
在com.itheima.domain
创建一个实体类Account
注意要建立一对一的关系映射
package com.itheima.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 +
'}';
}
}
在com.itheima.dao
创建一个IAccountDao
接口
配置Account
对User
的映射
在属性fetchType
中FetcheType
有三个值,LAZY
、EAGER
、DEFAULT
LAZY
:使用延迟加载
EAGER
:使用立即加载
DEFAULT
:使用默认值,即使用立即加载
一对一的时候我们使用立即加载
one=@One()
表示一对一或者一对多
many=@Many
()表示多对一或者多对多
package com.itheima.dao;
import com.itheima.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
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="com.itheima.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List<Account> findAll();
}
还需要在com.itheima.dao.IUserDao
添加一个方法findById
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{u id} ")
@ResultMap("userMap")
User findById(Integer userId);
创建一个测试类
com.itheima.test.AccountTest
package com.itheima.test;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
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.List;
public class AccountTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IAccountDao accountDao;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
accountDao = session.getMapper(IAccountDao.class);
}
@After
public void destroy()throws Exception{
session.commit();
session.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());
}
}
}
运行测试类testFindAll
方法,结果如下
5.2 一对多的查询配置
首先要在com.itheima.domain.User
实体类建立一对多的关系映射
package com.itheima.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable{
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
//一对多关系映射:一个用户对应多个账户
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}
配置com.itheima.dao.IUserDao
接口
一对多开启延迟加载
package com.itheima.dao;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
import java.util.Properties;
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "address",property = "userAddress"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(property = "accounts", column = "id", many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid" ))
})
List<User> findAll();
}
在com.itheima.dao.IAccountDao
添加一个方法findAccountByUid
/**
* 根据用户id查询账户信息
* @param userId
* @return
*/
@Select("select * from account where uid = #{id}")
List<Account> findAccountByUid(Integer userId);
测试类com.itheima.test.AnnotationCRUDTest
测试方法testFindAll
@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());
}
}
运行结果如下,延迟加载的效果也出来了
5. 注解开发使用二级缓存
在SpringMVC配置文件中配置开启(默认开启,也可以不用配)
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
然后只需要在接口Dao
中配置注解@CacheNamespace(blocking = true)
就可以了
@CacheNamespace(blocking = true)
public interface IUserDao{
}