Mybatis3
大纲
1、Mybatis中的延迟加载
什么是延迟加载
什么是立即加载
2、Mybatis中的缓存
什么是缓存
为什么使用缓存
什么样的数据能使用缓存,什么样的数据不能使用
Mybatis中的一级缓存和二级缓存
3、Mybatis中的注解开发
环境搭建
单表CRUD操作(代理Dao方式)
多表查询操作
缓存的配置
1、Mybatis中的延迟加载
问题:在一对多中,当我们有一个用户,它有100个账户。
在查询用户的时候,要不要把关联的账户查出来?
在查询账户的时候,要不要把关联的用户查出来?
在查询用户时,用户下的账户信息应该是,什么时候使用,什么时候查询的。
在查询账户时,账户的所属用户信息应该是随着账户查询时一起查询出来。
什么是延迟加载
在真正使用数据时才发起查询,不用的时候不查询。按需加载(懒加载)
什么是立即加载
不管用不用,只要一调用方法,马上发起查询。
在对应的四种表关系中:一对多,多对一,一对一,多对多
一对多,多对多:通常情况下我们都是采用延迟加载。
多对一,一对一:通常情况下我们都是采用立即加载。
创建工程->Maven ->不勾create from ->com.yu -> day04_eesy_01lazy(初始代码和 day03_eesy_03one2many一样,只留 findAll)
collection和association的区别
association是用于一对一和多对一,而collection是用于一对多的关系
1 使用 assocation 实现延迟加载(一对一或多对一)
注:一般在实际开发中,多对一不用延迟加载,此处只是为了演示assocation 的效果
https://mybatis.org/mybatis-3/zh/configuration.html#settings
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>
<!--开启Mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<package name="com.yu.domain"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置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>
<!--配置映射文件的位置-->
<mappers>
<!--<mapper resource="com/yu/dao/IUserDao.xml"></mapper>-->
<!--package标签是用于指定dao接口所在的包,当指定了之后就不需要再写mapper以及resource或者class了-->
<package name="com.yu.dao"></package>
</mappers>
</configuration>
IAccountDao.java
package com.yu.dao;
import com.yu.domain.Account;
import java.util.List;
public interface IAccountDao {
/**
* 查询所有账户及对应的用户信息
* @return
*/
List<Account> findAll();
}
IAccountDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yu.dao.IAccountDao">
<!--定义封装account和user的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 一对一的关系映射:配置封装user的内容 -->
<!--javaType:封装到哪个对象-->
<!--select属性指定的内容:查询用户 唯一标识-->
<association property="user" column="uid" javaType="user" select="com.yu.dao.IUserDao.findById">
</association>
</resultMap>
<!--查询所有账户及对应的用户信息-->
<select id="findAll" resultMap="accountUserMap">
SELECT * FROM account
</select>
</mapper>
AccountTest.java
package com.yu.test;
import com.yu.dao.IAccountDao;
import com.yu.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 SqlSession sqlSession;
private IAccountDao accountDao;
@Before//用于在测试方法执行之前执行
public void init() throws Exception{
//1 读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3 获取SqlSession对象
sqlSession = factory.openSession(true);
//4 获取dao的代理对象
accountDao = sqlSession.getMapper(IAccountDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
// 提交事务
//sqlSession.commit();
//6 释放资源
sqlSession.close();
in.close();
}
/**
* 查询所有账户及对应的用户信息
*/
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
for(Account account:accounts){
System.out.println("-------每个account信息-------");
System.out.println(account);
System.out.println(account.getUser());
}
}
}
IUserDao.java
package com.yu.dao;
import com.yu.domain.User;
import java.util.List;
/**
* 用户的持久层接口
*/
public interface IUserDao {
/**
* 查询所有的用户,及对应的账户信息
* @return
*/
List<User> findAll();
/**
* 根据id查询用户
* @param userId
* @return
*/
User findById(Integer userId);
}
IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yu.dao.IUserDao">
<!--定义User的resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!--配置user对象中accounts集合的映射-->
<collection property="accounts" ofType="account">
<id column="aid" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
<!--查询所有的用户,及对应的账户信息-->
<select id="findAll" resultMap="userAccountMap">
SELECT * FROM user u LEFT OUTER JOIN account a ON u.id = a.UID
</select>
<!--根据id查询用户-->
<select id="findById" parameterType="INT" resultType="user">
SELECT * FROM USER where id = #{uid}
</select>
</mapper>
2 使用 Collection 实现延迟加载(一对多)
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>
<!--开启Mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<package name="com.yu.domain"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置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>
<!--配置映射文件的位置-->
<mappers>
<!--<mapper resource="com/yu/dao/IUserDao.xml"></mapper>-->
<!--package标签是用于指定dao接口所在的包,当指定了之后就不需要再写mapper以及resource或者class了-->
<package name="com.yu.dao"></package>
</mappers>
</configuration>
IUserDao.java
package com.yu.dao;
import com.yu.domain.User;
import java.util.List;
/**
* 用户的持久层接口
*/
public interface IUserDao {
/**
* 查询所有的用户,及对应的账户信息
* @return
*/
List<User> findAll();
/**
* 根据id查询用户
* @param userId
* @return
*/
User findById(Integer userId);
}
IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yu.dao.IUserDao">
<!--定义User的resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!--配置user对象中accounts集合的映射-->
<collection property="accounts" ofType="account" select="com.yu.dao.IAccountDao.findAccountById" column="id">
</collection>
</resultMap>
<!--查询所有的用户,及对应的账户信息-->
<select id="findAll" resultMap="userAccountMap">
SELECT * FROM user
</select>
<!--根据id查询用户-->
<select id="findById" parameterType="INT" resultType="user">
SELECT * FROM USER where id = #{uid}
</select>
</mapper>
IAccountDao.java
package com.yu.dao;
import com.yu.domain.Account;
import java.util.List;
public interface IAccountDao {
/**
* 查询所有账户及对应的用户信息
* @return
*/
List<Account> findAll();
/**
* 根据用户id查询账户信息
* @param uid
* @return
*/
List<Account> findAccountById(Integer uid);
}
IAccountDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yu.dao.IAccountDao">
<!--定义封装account和user的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 一对一的关系映射:配置封装user的内容 -->
<!--javaType:封装到哪个对象-->
<!--select属性指定的内容:查询用户 唯一标识-->
<association property="user" column="uid" javaType="user" select="com.yu.dao.IUserDao.findById">
</association>
</resultMap>
<!--查询所有账户及对应的用户信息-->
<select id="findAll" resultMap="accountUserMap">
SELECT * FROM account
</select>
<!--根据用户id查询账户信息-->
<select id="findAccountById" resultType="account">
SELECT * FROM account WHERE uid = #{uid}
</select>
</mapper>
UserTest.java
package com.yu.test;
import com.yu.dao.IUserDao;
import com.yu.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.List;
/**
* 测试
*/
public class UserTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before//用于在测试方法执行之前执行
public void init() throws Exception{
//1 读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3 获取SqlSession对象
sqlSession = factory.openSession(true);
//4 获取dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
// 提交事务
//sqlSession.commit();
//6 释放资源
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());
}
}
}
2、Mybatis中的缓存
什么是缓存
存在于内存中的临时数据。
为什么使用缓存
减少和数据库的交互次数,提高执行效率。
什么样的数据能使用缓存,什么样的数据不能使用
适用于缓存:
经常查询并且不经常改变的。
数据的正确与否对最终结果影响不大的。
不适用于缓存:
经常改变的数据
数据的正确与否对最终结果影响很大的。
例如:商品的库存,银行的汇率,股市的牌价。
Mybatis中的一级缓存和二级缓存
一级缓存:(自带)
它指的是Mybatis中SqlSession对象的缓存。
当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中。
该区域的结构是一个Map。当我们再次查询同样的数据,mybatis会先去sqlsession中
查询是否有,有的话直接拿出来用。
当SqlSession对象消失时,mybatis的一级缓存也就消失了。
一级缓存是 SqlSession 范围的缓存,当调用 SqlSession 的修改,添加,删除,commit(),close()等方法时,就会清空一级缓存。??????
二级缓存:
它指的是Mybatis中SqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建的SqlSession共享其缓存。
二级缓存的使用步骤:
第一步:让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)(默认打开)
第二步:让当前的映射文件支持二级缓存(在IUserDao.xml中配置)
第三步:让当前的操作支持二级缓存(在select标签中配置)
一级缓存测试
创建工程->Maven ->不勾create from ->com.yu -> day04_eesy_02cache(初始代码和 day03_eesy_03one2many一样,删去Account相关)
User.java
package com.yu.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 +
// '}';
// }
}
IUserDao.java
package com.yu.dao;
import com.yu.domain.User;
import java.util.List;
/**
* 用户的持久层接口
*/
public interface IUserDao {
/**
* 查询所有的用户,及对应的账户信息
*/
List<User> findAll();
/**
* 根据id查询用户
* @param uid
* @return
*/
User findById(Integer uid);
/**
* 更新用户信息
* @param user
*/
void updateUser(User user);
}
IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yu.dao.IUserDao">
<!--查询所有的用户,及对应的账户信息-->
<select id="findAll" resultType="user">
SELECT * FROM user
</select>
<!--根据id查询用户-->
<select id="findById" parameterType="INT" resultType="user">
SELECT * FROM USER where id = #{uid}
</select>
<!--更新用户信息-->
<select id="updateUser" parameterType="user">
update user set username = #{username},address = #{address} where id = #{id};
</select>
</mapper>
UserTest.java
package com.yu.test;
import com.yu.dao.IUserDao;
import com.yu.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.List;
/**
* 测试
*/
public class UserTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
private SqlSessionFactory factory;
@Before//用于在测试方法执行之前执行
public void init() throws Exception{
//1 读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获取SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3 获取SqlSession对象
sqlSession = factory.openSession();
//4 获取dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
// 提交事务
sqlSession.commit();
//6 释放资源
sqlSession.close();
in.close();
}
@Test
public void testFirstLevelCache(){
User user1 = userDao.findById(41);
System.out.println(user1);
// sqlSession.close();
// //再次获取SqlSession对象
// sqlSession = factory.openSession();
// userDao =sqlSession.getMapper(IUserDao.class);
//sqlSession.clearCache();//此方法也可以清空缓存
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user1 == user2);
}
@Test
public void testClearCache(){
User user1 = userDao.findById(41);
System.out.println(user1);
user1.setUsername("update clear cache user");
user1.setAddress("北京市海淀区");
userDao.updateUser(user1);
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user1 == user2);
}
}
二级缓存测试
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>
<!--让Mybatis框架支持二级缓存(默认打开)-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<package name="com.yu.domain"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置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>
<!--配置映射文件的位置-->
<mappers>
<!--<mapper resource="com/yu/dao/IUserDao.xml"></mapper>-->
<!--package标签是用于指定dao接口所在的包,当指定了之后就不需要再写mapper以及resource或者class了-->
<package name="com.yu.dao"></package>
</mappers>
</configuration>
IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yu.dao.IUserDao">
<!--开启user的映射支持二级缓存-->
<cache/>
<!--查询所有的用户,及对应的账户信息-->
<select id="findAll" resultType="user">
SELECT * FROM user
</select>
<!--根据id查询用户-->
<!--让当前的操作支持二级缓存-->
<select id="findById" parameterType="INT" resultType="user" useCache="true">
SELECT * FROM USER where id = #{uid}
</select>
<!--更新用户信息-->
<select id="updateUser" parameterType="user">
update user set username = #{username},address = #{address} where id = #{id};
</select>
</mapper>
SecondLevelCacheTest
package com.yu.test;
import com.yu.dao.IUserDao;
import com.yu.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;
/**
* 测试
*/
public class SecondLevelCacheTest {
private InputStream in;
private SqlSessionFactory factory;
@Before//用于在测试方法执行之前执行
public void init() throws Exception{
//1 读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获取SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
in.close();
}
@Test
public void testSecondLevelCache(){
SqlSession sqlSession1 = factory.openSession();
IUserDao dao1 = sqlSession1.getMapper(IUserDao.class);
User user1 = dao1.findById(41);
System.out.println(user1);
sqlSession1.commit();
sqlSession1.close();//一级缓存消失
SqlSession sqlSession2 = factory.openSession();
IUserDao dao2 = sqlSession2.getMapper(IUserDao.class);
User user2 = dao2.findById(41);
System.out.println(user2);
sqlSession2.commit();
sqlSession2.close();
System.out.println(user1 == user2);
}
}
3、Mybatis中的注解开发
环境搭建
单表CRUD操作(代理Dao方式)
多表查询操作
缓存的配置
常用注解说明
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
环境搭建
创建工程->Maven ->不勾create from
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.yu</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>
导入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
导入jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=root
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.yu.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.yu.dao"></package>
</mappers>
</configuration>
User
package com.yu.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;
//get set toString略
}
IUserDao
package com.yu.dao;
import com.yu.domain.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 在mybatis中针对CURD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
}
MybatisAnnoTest
package com.yu.test;
import com.yu.dao.IUserDao;
import com.yu.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 {
/**
* 测试基于注解的mybatis使用
*/
public static void main(String[] args) throws Exception {
//1 获取字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 根据字节输入流构建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3 根据SqlSessionFactory生产一个SqlSession
SqlSession session = factory.openSession();
//4 使用SqlSession获取Dao的代理对象
IUserDao userDao = session.getMapper(IUserDao.class);
//5 执行Dao的方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
session.close();
in.close();
}
}
单表CRUD操作(代理Dao方式)
- 在mybatis中针对CURD一共有四个注解
@Select @Insert @Update @Delete
增 保存
IUserDao
/**
* 增 保存
* @param user
*/
@Insert("insert into user(username,sex,birthday,address) values (#{username},#{sex},#{birthday},#{address})")
void saveUser(User user);
AnnotationCRUDTest
package com.yu.test;
import com.yu.dao.IUserDao;
import com.yu.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.IOException;
import java.io.InputStream;
import java.util.Date;
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 destory() throws IOException {
session.commit();
session.close();
in.close();
}
@Test
public void testSave(){
User user = new User();
user.setUsername("mybatis annotation");
user.setAddress("上海");
user.setSex("男");
user.setBirthday(new Date());
userDao.saveUser(user);
}
}
删 根据id删除用户
IUserDao
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id = #{id}")
void deleteUser(Integer userId);
测试
public void testDelete(){
userDao.deleteUser(58);
}
改 更新用户
IUserDao
/**
* 改 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id = #{id}")
void updateUser(User user);
测试
@Test
public void testUpdate(){
User user = new User();
user.setId(59);
user.setUsername("annotationUpdate");
user.setBirthday(new Date());
user.setSex("女");
user.setAddress("河北");
userDao.updateUser(user);
}
查
根据id查询用户
IUserDao
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id = #{id}")
User findById(Integer userId);
测试
@Test
public void testFindOne(){
User user = userDao.findById(57);
System.out.println(user);
}
根据用户名称模糊查询
方法一
IUserDao
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like #{username}")
List<User> findUserByName(String username);
测试
@Test
public void testFindByName(){
List<User> users = userDao.findUserByName("%mybatis%");
for(User user : users){
System.out.println(user);
}
}
方法二
IUserDao
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like '%${value}%'")
List<User> findUserByName(String username);
测试
@Test
public void testFindByName(){
List<User> users = userDao.findUserByName("mybatis");
for(User user : users){
System.out.println(user);
}
}
查询总用户数量
IUserDao
/**
* 查询总用户数量
* @return
*/
@Select("select count(*) from user")
int findTotalUser();
测试
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
}
解决实体类属性和数据库表中列的对应不一致
IUserDao
package com.yu.dao;
import com.yu.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* 在mybatis中针对CURD一共有四个注解
* @Select @Insert @Update @Delete
*/
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 = "birthday",property = "userBirthday"),
@Result(column = "sex",property = "userSex"),
@Result(column = "address",property = "userAddress")
})
List<User> findAll();
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id = #{id}")
@ResultMap(value = {"userMap"})
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like #{username}")
@ResultMap(value = {"userMap"})
List<User> findUserByName(String username);
}
多表查询操作
注解开发一对一的查询
IAccountDao
package com.yu.dao;
import com.yu.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 {
@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(column = "uid",property = "user",one=@One(select="com.yu.dao.IUserDao.findById",fetchType = FetchType.EAGER))
})
List<Account> findAll();
}
IUserDao
package com.yu.dao;
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id = #{id}")
@ResultMap(value = {"userMap"})
User findById(Integer userId);
Account
package com.yu.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;
}
测试
@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());
}
}
注解开发一对多的查询
IUserDao
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id = "userMap",value = {
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "birthday",property = "userBirthday"),
@Result(column = "sex",property = "userSex"),
@Result(column = "address",property = "userAddress"),
@Result(column = "id",property = "accounts",
many = @Many(select = "com.yu.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
IAccountDao
/**
* 根据用户id查询账户信息
* @param userId
* @return
*/
@Select("select * from account where uid = #{id}")
List<Account> findAccountByUid(Integer userId);
User
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;
}
测试
@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 testFindOne(){
User user = userDao.findById(57);
System.out.println(user);
User user2 = userDao.findById(57);
System.out.println(user2);
System.out.println(user == user2);
}
二级缓存默认不开启
public class SecondLevelCatchTest {
private InputStream in;
private SqlSessionFactory factory;
@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
}
@After
public void destory() throws IOException {
in.close();
}
@Test
public void testFindOne(){
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
User user = userDao.findById(57);
System.out.println(user);
session.close();//释放一级缓存
SqlSession session1 = factory.openSession();
IUserDao userDao1 = session1.getMapper(IUserDao.class);
User user1 = userDao1.findById(57);
System.out.println(user1);
}
}
开启二级缓存
SqlMapConfig 中添加
<!--配置开启二级缓存-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
IUserDao 中添加
@CacheNamespace(blocking = true)
public interface IUserDao {