1. Mybatis中的延迟加载
1: 问题:在一对多中,当我们有一个用户,它有100个账户。
在查询用户的时候,要不要把关联的账户查出来?
在查询账户的时候,要不要把关联的用户查出来?
在查询用户时,用户下的账户信息应该是,什么时候使用,什么时候查询的。
在查询账户时,账户的所属用户信息应该是随着账户查询时一起查询出来。
2: 什么是延迟加载
在真正使用数据时才发起查询,不用的时候不查询。按需加载(懒加载)
好处:
先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询
多张表速度要快。
坏处:
因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要
消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。
3: 什么是立即加载
不管用不用,只要一调用方法,马上发起查询。
4: 在对应的四种表关系中:一对多,多对一,一对一,多对多
一对多,多对多:通常情况下我们都是采用延迟加载。
多对一,一对一:通常情况下我们都是采用立即加载。
5: 多对一 association 只查账户信息,不查用户信息。
1: 账户的持久层 DAO 接口
public class AccountUser extends Account {
private String username;
private String address;
}
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
private User user;
}
public interface IAccountDao {
/**
* 查询所有账户
*
* @return
*/
List<Account> findAll();
/**
* 查询所有账户,同时获取账户的所属用户名称以及它的地址信息
*
* @return
*/
List<AccountUser> findAccount();
}
2: 账户的持久层映射文件
<?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.demos.dao.IAccountDao">
<!-- 建立对应关系 -->
<resultMap type="account" id="accountMap">
<id column="aid" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!-- 它是用于指定从表方的引用实体属性的
column:主信息表(当前查询的account表)和 user 表关联的字段
-->
<association property="user" javaType="user"
select="com.demos.dao.IUserDao.findById" column="uid">
</association>
</resultMap>
<select id="findAll" resultMap="accountMap">
select * from account
</select>
</mapper>
select: 填写我们要调用的 select 映射的 id
column : 填写我们要传递给 select 映射的参数
3: 用户的持久层接口和映射文件
public interface IUserDao {
/**
* 根据 id 查询
* @param userId
* @return
*/
User findById(Integer userId);
}
<?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.demos.dao.IUserDao">
<!-- 根据 id 查询 -->
<select id="findById" resultType="user" parameterType="int" >
select * from user where id = #{uid}
</select>
</mapper>
4: 开启 Mybatis 的延迟加载策略
我们需要在 Mybatis 的配置文件 SqlMapConfig.xml 文件中添加延迟加载的配置。
lazyLoadingEnabled: 默认值为false
aggressiveLazyLoading: false(true in <=3.4.1)
<!-- 开启延迟加载的支持 -->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
5: 编写测试只查账户信息不查用户信息。
@Test
public void testFindAll() {
//6.执行操作
List<Account> accounts = accountDao.findAll();
}
发现因为本次只是将Account对象查询出来放入List集合中,并没有涉及到 User对象,
所以就没有发出 SQL 语句查询账户所关联的 User 对象的查询。
6. 一对多 collection 完成加载用户对象时,查询该用户所拥有的账户信息。
1: 在 User 实体类中加入 List<Account>属性
private List<Account> accounts;
2: 编写用户和账户持久层接口的方法
/**
* 查询所有用户,同时获取出每个用户下的所有账户信息
* @return
*/
List<User> findAll();
3: 编写用户持久层映射配置
<resultMap type="user" id="userMap">
<id column="id" property="id"></id>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!-- collection 是用于建立一对多中集合属性的对应关系
ofType 用于指定集合元素的数据类型
select 是用于指定查询账户的唯一标识(账户的 dao 全限定类名加上方法名称)
column 是用于指定使用哪个字段的值作为条件查询
-->
<collection property="accounts" ofType="account"
select="com.demos.dao.IAccountDao.findByUid"
column="id">
</collection>
</resultMap>
<!-- 配置查询所有操作 -->
<select id="findAll" resultMap="userMap">
select * from user
</select>
<collection>标签:主要用于加载关联的集合对象
select 属性:用于指定查询account列表的sql 语句,所以填写的是该 sql 映射的 id
column 属性:用于指定 select 属性的 sql 语句的参数来源,上面的参数来自于 user 的 id 列,所以就写成 id 这一个字段名了
4: 编写账户持久层映射配置
<!-- 根据用户 id 查询账户信息 -->
<select id="findByUid" resultType="account" parameterType="int">
select * from account where uid = #{uid}
</select>
5: 测试只加载用户信息
@Test
public void testFindAll() {
//6.执行操作
List<User> users = userDao.findAll();
}
2. Mybatis 缓存
* 什么是缓存
存在于内存中的临时数据。
* 为什么使用缓存
减少和数据库的交互次数,提高执行效率。
* 什么样的数据能使用缓存,什么样的数据不能使用
适用于缓存:
经常查询并且不经常改变的。
数据的正确与否对最终结果影响不大的。
不适用于缓存:
经常改变的数据
数据的正确与否对最终结果影响很大的。
例如:商品的库存,银行的汇率,股市的牌价。
* Mybatis中的一级缓存和二级缓存
一级缓存: SqlSession 级别
它指的是Mybatis中SqlSession对象的缓存。
当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中。
该区域的结构是一个Map。当我们再次查询同样的数据,mybatis会先去sqlsession中
查询是否有,有的话直接拿出来用。
当SqlSession对象消失时,mybatis的一级缓存也就消失了。
二级缓存: mapper 级别
它指的是Mybatis中SqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建的SqlSession共享其缓存。
二级缓存的使用步骤:
第一步:让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)
第二步:让当前的映射文件支持二级缓存(在IUserDao.xml中配置)
第三步:让当前的操作支持二级缓存(在select标签中配置)
1: Mybatis 一级缓存
* 一级缓存是 SqlSession 级别的缓存,只要 SqlSession 没有 flush 或 close,它就存在。
1: 编写用户持久层 Dao 接口
public interface IUserDao {
/**
* 根据 id 查询
* @param userId
* @return
*/
User findById(Integer userId);
}
2: 编写用户持久层映射文件
<?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.demos.dao.IUserDao">
<!-- 根据 id 查询 -->
<select id="findById" resultType="user" parameterType="int" useCache="true">
select * from user where id = #{uid}
</select>
</mapper>
3: 编写测试方法
@Test
public void testFindById() {
User user = userDao.findById(41);
System.out.println("第一次查询的用户:"+user);
User user2 = userDao.findById(41);
System.out.println("第二次查询用户:"+user2);
System.out.println(user == user2);
}
发现,虽然在上面的代码中我们查询了两次,但最后只执行了一次数据库操作,这就是 Mybatis
提供给我们的一级缓存在起作用了。
4: 一级缓存的分析
* 一级缓存是 SqlSession 范围的缓存,当调用 SqlSession 的修改,添加,删除,commit(),close()等方法时,就会清空一级缓存。
* 测试一级缓存的清空
/**
* 测试一级缓存
*/
@Test
public void testFirstLevelCache(){
User user1 = userDao.findById(41);
System.out.println(user1);
// sqlSession.close();
//再次获取 SqlSession 对象
// sqlSession = factory.openSession();
sqlSession.clearCache();//此方法也可以清空缓存
userDao = sqlSession.getMapper(IUserDao.class);
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user1 == user2);
}
* 当执行sqlSession.close()后,再次获取sqlSession并查询id=41的User对象时,又
重新执行了sql 语句,从数据库进行了查询操作。
2: Mybatis 二级缓存
* 二级缓存是 mapper 映射级别的缓存,多个 SqlSession 去操作同一个 Mapper 映射的 sql
语句,多个SqlSession 可以共用二级缓存,二级缓存是跨 SqlSession 的。
* 如果 SqlSession 去执行相同 mapper 映射下 sql,执行 commit 提交,将会清空该 mapper
映射下的二级缓存区域的数据。
* 注意事项
当我们在使用二级缓存时,所缓存的类一定要实现 java.io.Serializable 接口,
这种就可以使用序列化方式来保存对象。
1: 第一步:在 SqlMapConfig.xml 文件开启二级缓存
<settings>
<!-- 开启二级缓存的支持
1.指定使用的二级缓存的类型(自带的,第三方插件(ehcache,redis))
<cache type="org.apache.ibatis.cache.impl.PerpetualCache"></cache>
-->
<setting name="cacheEnabled" value="true"/>
</settings>
* 因为 cacheEnabled 的取值默认就为 true,所以这一步可以省略不配置。为 true
代表开启二级缓存;为false 代表不开启二级缓存。
2: 第二步:配置相关的 Mapper 映射文件
<cache>标签表示当前这个mapper映射将使用二级缓存,区分的标准就看mapper的namespace值
<?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.demos.dao.IUserDao">
<!-- 开启二级缓存的支持 -->
<cache></cache>
</mapper>
3: 第三步:配置 statement 上面的 useCache 属性
<!-- 根据 id 查询 -->
<select id="findById" resultType="user" parameterType="int" useCache="true">
select * from user where id = #{uid}
</select>
注意: 将 UserDao.xml 映射文件中的<select>标签中设置 useCache=”true”代表当前这个
statement 要使用二级缓存,如果不使用二级缓存可以设置为 false。
针对每次查询都需要最新的数据 sql,要设置成 useCache=false,禁用二级缓存。
4: 二级缓存测试
@Test
public void testFirstLevelCache(){
SqlSession sqlSession1 = factory.openSession();
IUserDao dao1 = sqlSession1.getMapper(IUserDao.class);
User user1 = dao1.findById(41);
System.out.println(user1);
sqlSession1.close();//一级缓存消失
SqlSession sqlSession2 = factory.openSession();
IUserDao dao2 = sqlSession2.getMapper(IUserDao.class);
User user2 = dao2.findById(41);
System.out.println(user2);
sqlSession2.close();
System.out.println(user1 == user2); //false
}
发现执行了两次查询,并且在执行第一次查询后,我们关闭了一级缓存,再去执行第二次查询时,
我们发现并没有对数据库发出 sql 语句,所以此时的数据就只能是来自于我们所说的二级缓存。
3. Mybatis 注解开发
1: mybatis 的常用注解说明
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
2: 注解实现基本 CRUD
/**
* 查询所有用户
*
* @return
*/
@Select("select * from user")
List<User> findAll();
/**
* 根据id查找用户
*
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
User findById(Integer userId);
/**
* 保存用户
*
* @return
*/
@Insert("insert into user(username,sex,birthday,address) values (#{username},#{sex},#{birthday},#{address})")
@SelectKey(keyColumn = "id", keyProperty = "id", resultType = Integer.class, before = false, statement = {
" select last_insert_id()" })
int saveUser(User user);
/**
* 更新用户
*
* @param user
* @return
*/
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ")
int updateUser(User user);
/**
* 删除用户
*
* @param userId
* @return
*/
@Delete("delete from user where id = #{uid} ")
int deleteUser(Integer userId);
/**
* 模糊查询
*
* @param name
* @return
*/
// @Select("select * from user where username like #{username} ")
@Select("select * from user where username like '%${value}%' ")
List<User> findByName(String name);
/**
* 查询使用聚合函数
*
* @return
*/
@Select("select count(*) from user ")
int findTotal();
3: 使用注解实现复杂关系映射开发
1: 复杂关系映射的注解说明
@Results 注解
代替的是标签<resultMap>
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({@Result(),@Result()})或@Results(@Result())
@Resutl 注解
代替了 <id>标签和<result>标签
@Result 中 属性介绍:
id 是否是主键字段
column 数据库的列名
property 需要装配的属性名
one 需要使用的@One 注解(@Result(one=@One)()))
many 需要使用的@Many 注解(@Result(many=@many)()))
@One 注解(一对一)
代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One 注解属性介绍:
select 指定用来多表查询的 sqlmapper
fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。。
使用格式:
@Result(column=" ",property="",one=@One(select=""))
@Many 注解(多对一)
代替了<Collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType
(一般为 ArrayList)但是注解中可以不定义;
使用格式:
@Result(property="",column="",many=@Many(select=""))
2: 注解实现一对一复杂关系映射及延迟加载
* 需求:
加载账户信息时并且加载该账户的用户信息,根据情况可实现延迟加载。(注解方式实现)
1: Account
//多对一关系映射:从表方应该包含一个主表方的对象引用
private User user;
2: 添加账户的持久层接口并使用注解配置
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(column="uid",property="user",
one=@One(select="com.demos.dao.IUserDao.findById",
fetchType=FetchType.LAZY) )
})
List<Account> findAll();
}
3: 添加用户的持久层接口并使用注解配置
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="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday")
})
List<User> findAll();
/**
* 根据 id 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
}
3: 使用注解实现一对多复杂关系映射
* 需求:
查询用户信息时,也要查询他的账户列表。使用注解方式实现。
1: User 实体类加入 List<Account>
//一对多关系映射:主表方法应该包含一个从表方的集合引用
private List<Account> accounts;
2: 编写用户的持久层接口并使用注解配置
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="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday"),
@Result(column="id",property="accounts",
many=@Many(
select="com.demos.dao.IAccountDao.findByUid",
fetchType=FetchType.LAZY
) )
})
List<User> findAll();
}
@Many:
相当于<collection>的配置
select 属性:代表将要执行的 sql 语句
fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值
3: 编写账户的持久层接口并使用注解配置
public interface IAccountDao {
/**
* 根据用户 id 查询用户下的所有账户
* @param userId
* @return
*/
@Select("select * from account where uid = #{uid} ")
List<Account> findByUid(Integer userId);
}
4: 基于注解的二级缓存
1: 在 SqlMapConfig 中开启二级缓存支持
<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 默认为true-->
<setting name="cacheEnabled" value="true"/>
</settings>
2: 在持久层接口中使用注解配置二级缓存
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {}
4. 逆向工程
* 导入jar包 mybatis-generator-core-1.3.2.jar
1. com.demos.utils 包下面导入 generator.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis01" userId="root"
password="root">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
userId="yycg"
password="yycg">
</jdbcConnection> -->
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.demos.bean"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.demos.dao"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.demos.dao"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<!-- <table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table> -->
<table tableName="user"></table>
</context>
</generatorConfiguration>
2. 解析逆向工程的配置文件 GeneratorSqlmap.java
public class GeneratorSqlmap {
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("D:\\eclipse-jee-2018-09-win32-x86_64\\eclipse\\ThirdSpace\\mybatis02\\src\\com\\demos\\utils\\generator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
3. 测试:
public class App {
public static void main(String[] args) throws IOException {
String resource = "com/demos/service/SqlMapConifg.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper um= sqlSession.getMapper(UserMapper.class);
//查询总的记录数
int rows = um.countByExample(null);
System.out.println(rows);
//查询性别为 男的 人的信息
UserExample ue = new UserExample();
Criteria cc = ue.createCriteria();
cc.andSexEqualTo("男");
List<User> uList = um.selectByExample(ue);
System.out.println(uList);
//插入一条
User u=new User();
u.setSex("男");
u.setUsername("张明");
um.insert(u);
sqlSession.commit();
sqlSession.close();
}
}