注:前两部分只是大概介绍
重点是第三部分的 MyBatis注解方式进行开发
在真正使用数据时才发起查询,不用的时候不查询;按需加载(懒加载);
不管用不用,只要一调用方法,马上发起查询;
一级缓存是 SQLSession 范围的缓存,当调用 SQLSession 的修改、添加、删除、commit()、close() 等方法时,就会清空一级缓存;
用注解方式进行开发,可替代原来的配置文件 IUserDao.xml;
这里直接给出整个项目的文件目录
pom.xml 文件内容如下:
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>MyBatisTest2artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.15version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.12version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>RELEASEversion>
<scope>testscope>
dependency>
dependencies>
project>
jdbcConfig.properties 和 log4j.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.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
<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>
<mappers>
<package name="dao">package>
mappers>
configuration>
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;
(根据前面的目录,在适当位置创建即可)
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 +
'}';
}
}
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();
}
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 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);
}
}
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;
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 +
'}';
}
}
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 +
'}';
}
}
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);
}
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();
}
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());
}
}
}
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 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);
}
}
<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>
<mappers>
<package name="dao">package>
mappers>
configuration>
@CacheNamespace(blocking = true) //开启二级缓存
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();
}
}