您的位置:首页 > 编程语言 > Java开发

JAVAWEB开发之mybatis详解(二)——高级映射、查询缓存、mybatis与Spring整合以及懒加载的配置和逆向工程

2017-06-16 16:35 1226 查看

mybatis基础知识回顾

1. mybatis是什么?

mybatis是一个持久层框架,是Apache下的开源项目,前身是ibatis,是一个不完全的ORM框架,mybatis提供输入和输出的映射,需要程序员自己手动写SQL语句,mybatis重点对SQL语句进行灵活操作。
适用场合:需求变化频繁,数据模型不固定的项目,例如:互联网项目。

2.mybatis架构:

SqlMapConfig.xml(名称不固定),配置内容:数据源、事务、properties、typeAliases、settings、mappers配置。
SqlSessionFactory:会话工厂,作用是创建SqlSession,实际开发中以单例模式管理SqlSessionFactory。
SqlSession:会话,是一个面向用户(程序员)的接口,使用mapper代理方法开发是不需要程序员直接调用Sqlsession的方法。它是线程不安全的,最佳使用场合是方法体内。

3.mybatis开发DAO的方法

3.1 原始DAO开发方法,需要程序员编写Dao接口和实现类,此方法在当前企业中还有使用因为ibatis用的就是这种原始的Dao开发方式。
3.2 mapper代理方法,程序员只需要编写mapper接口(相当于DAO接口),mybatis自动根据mapper接口和mapper接口对应的statement自动生成代理对象(接口实现类对象),注意使用mapper代理方法开发需要遵循以下规则:

mapper.xml中namespace是mapper接口的全限定名。
mapper.xml中statement的id为mapper接口的方法名。
mapper.xml中statement输入类型(parameterType)和mapper接口方法输入参数类型一致。
mapper.xml中statement输出类型(resultType)和mapper接口方法返回结果类型一致。

resultType和resultMap都可以完成输出映射:
resultType映射要求SQL查询的列名和输出映射pojo类型的属性名一致。
resultMap映射时对SQL查询的列名和输出映射pojo类型的属性名做一个对应关系。
4.动态SQL:
#{}和${}完成输入参数的属性值获取,通过OGNL获取parameterType指定的pojo的属性名。
#{}:占位符号,好处是防止SQL注入。
${}: SQL拼接符号,无法防止SQL注入。
if、where以及foreach的使用。

mybatis重点高级知识清单

1.使用resultMap完成高级映射(重点)
—|学习商品订单数据模型(一对一、一对多、多对多)
—|resultMap实现一对一、一对多、多对多
—|延迟加载
2.查询缓存(重点)
—|一级缓存
—|二级缓存
3.mybatis和Spring的整合(重点)
4.mybatis逆向工程(常用)

商品订单数据模型



技巧总结:学会在企业中如何去分析陌生表的数据模型
1.学习单表记录了什么东西(去学习理解需求)
2.学习单表重要字段的意义(优先学习不能为空的字段)
3.学习表与表之间的关系(一对一、一对多、多对多)
通过表的外键分析表之间的关系。
注意:分析表与表之间的关系是建立在业务意义基础之上的。



用户表user:记录了购买商品的用户
订单表orders:记录了用户所创建的订单信息
订单明细表orderdetail:记录了用户所创建订单的详细信息
商品信息表items:记录了商家提供的商品信息。
分析表与表之间的订单关系:
(1) 用户表user和订单orders:
user—>orders: 一个用户可以创建多个订单 多对多
orders—>user: 一个订单只能由一个用户创建 一对一
(2) 订单表orders和订单明细表orderdetail:
orders—>orderdetail: 一个订单可以包括多个订单明细 一对多
orderdetail—>orders: 一个订单明细只能属于一个订单 一对一
(3)订单明细orderdetail和商品信息items
orderdetail—>items: 一个订单明细只能对应一个商品信息 一对一
items—>orderdetail: 一个商品对应多个订单明细 一对多

一对一查询

需求

查询订单信息关联查询用户信息

sql语句

查询语句:
先确定主查询表:订单信息表
再确定关联查询表:用户信息
通过orders关联穿用户使用user_id一个外键,根据一条订单数据只能查询出一条用户记录就可以使用内连接

[sql]
view plain
copy

SELECT
orders.*, user.username, user.sex
FROM
orders,
user
WHERE
orders.user_id = user.id;



使用resultType实现

创建PO类

创建基础表单的PO类



一对一查询映射的pojo

创建pojo包括 订单信息和用户信息,resultType才可以完成映射
创建OrderCustom作为自定义pojo,继承 SQL查询中列最多的POJO类

[java]
view plain
copy

public class OrderCustom extends Orders {
//补充用户信息
private String username;
private String sex;
private String address;
//提供对应的setter和getter方法
......
}

mapper.xml

[html]
view plain
copy

<!-- 一对一查询使用resultType完成
查询订单关联查询用户信息
-->
<select id="findOrderUserList" resultType="orderCustom">
SELECT
orders.*, user.username, user.sex
FROM
orders,
user
WHERE
orders.user_id = user.id;
</select>

mapper.java

[java]
view plain
copy

public interface OrdersMapperCustom {
//一对一查询,查询订单关联查询用户,使用resultType
public List<OrderCustom> findOrderUserList() throws Exception;
}

测试代码

[java]
view plain
copy

@Test
public void testFindOrderUserList() throws Exception{
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建mapper代理对象
OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
// 调用方法
List<OrderCustom> list = ordersMapperCustom.findOrderUserList();

System.out.println(list);
}

使用resultMap实现一对一

resultMap映射思路

resultMap提供一对一关联查询映射和一对多关联查询映射,一对一映射思路:将关联查询的信息映射到pojo中,如下:
在Orders类中创建一个user属性,将关联查询到的信息映射到User属性中。如下所示:

[java]
view plain
copy

public class Orders {
private Integer id;
private Integer userId;
private String number; //商品编号

private Date createtime;

private String note;

//关联用户信息
private User user;
.....

mapper.xml

[html]
view plain
copy

<!-- 一对一查询使用resultMap完成
查询订单关联查询用户信息
-->
<select id="findOrderUserListResultMap" resultMap="ordersUserResultMap">
SELECT
orders.*, user.username, user.sex
FROM
orders,
user
WHERE
orders.user_id = user.id;
</select>

resultMap定义

[html]
view plain
copy

<!-- 一对一查询resultMap -->
<resultMap type="test.lx.mybatis.po.Orders" id="ordersUserResultMap">
<!-- 完成了订单信息的映射配置 -->
<!-- id:订单关联用户查询的唯一标识 -->
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>

<!-- 下边完成关联信息的映射
association: 用于对关联信息映射到单个pojo
property: 要将关联信息映射到orders的哪个属性中
javaType: 关联信息映射到orders的属性类型,是user类型
-->
<association property="user" javaType="user">
<!-- id:关联信息的唯一标识 -->
<!-- property:要映射到所关联表中的哪个属性 -->
<id column="user_id" property="id"/>
<!-- result就是普通列的映射 -->
<result column="username" property="username"/>
<result column="sex" property="sex"/>
</association>
</resultMap>

注意的是:两个id的配置以及column的配置 外层的id配置一般指主查询表的主键,内层一般指的是关联查询的外键,共同点是其column的值都为执行其SQL语句查询出来的名称。起property是对应查询表的PO类中的属性名。



mapper.java

[java]
view plain
copy

// 一对一查询,查询订单关联查询用户,使用resultMap
public List<Orders> findOrderUserListResultMap() throws Exception;

小结

resultType:要自定义pojo 保证SQL查询列名要和pojo的属性对应,这种方法相对较简单,所以应用广泛。
resultMap:使用association完成一对一映射需要配置resultMap,过程有点复杂,如果要实现延迟加载就只能使用resultMap来进行实现,如果为了方便对关联信息的解析,也可使用association将关联信息映射到pojo中方便解析。

一对多查询

需求

查询所有订单信息及订单下的订单明细信息

SQL语句

主查询表:订单表
关联查询表:订单明细

[sql]
view plain
copy

SELECT
orders.*,
user.username,
user.sex ,
orderdetail.id orderdetail_id,
orderdetail.items_num,
orderdetail.items_id
FROM
orders,
USER,
orderdetail
WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id

查询结果



需要将订单明细内容设置到对应的订单中

resultMap进行一对多映射思路

resultMap提供collection完成关联信息映射到集合对象中。
在orders类中创建集合属性orderdetails:

[java]
view plain
copy

public class Orders {
private Integer id;
private Integer userId;
private String number; //商品编号

private Date createtime;

private String note;

//关联用户信息
private User user;

//订单明细
private List<OrderDetail> orderDetails;
//
......

mapper.xml

[html]
view plain
copy

<!-- 一对多查询使用resultMap完成
查询订单关联查询订单明细
-->
<select id="findOrderAndOrderdetails" resultMap="orderAndOrderDetails">
SELECT
orders.*,
user.username,
user.sex ,
orderdetail.id orderdetail_id,
orderdetail.items_num,
orderdetail.items_id
FROM
orders,
USER,
orderdetail
WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id
</select>

resultMap定义

[html]
view plain
copy

<!-- 一对多,查询订单以及订单明细 -->
<resultMap type="orders" id="orderAndOrderDetails" extends="ordersUserResultMap">
<!-- 映射订单信息,和用户信息,这里使用继承 ordersUserResultMap-->

<!-- 映射订单明细信息
property: 要将关联信息映射到orders的哪个属性中
ofType: 集合中的pojo属性
-->
<collection property="orderDetails" ofType="test.lx.mybatis.po.OrderDetail">
<!-- id: 关联信息订单明细的唯一标识
property: Orderdetail的属性名
-->
<id column="orderdetail_id" property="id"/>
<result column="items_num" property="itemsNum"/>
<result column="items_id" property="itemsId"/>
</collection>
</resultMap>

mapper.java

[java]
view plain
copy

// 一对多查询,查询订单关联查询订单明细,使用resultMap
public List<Orders> findOrderAndOrderdetails() throws Exception;

测试代码

[java]
view plain
copy

//一对多查询使用resultMap
@Test
public void testFindOrderAndOrderdetails() throws Exception{
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建mapper代理对象
OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);

//调用方法
List<Orders> list = ordersMapperCustom.findOrderAndOrderdetails();
for (Orders orders : list) {
System.out.println(orders.getUser().getUsername()+" "+orders.getOrderDetails().size());
}
System.out.println(list);
}

一对多查询[复杂]

需求

查询所有用户信息,关联查询订单及商品信息,订单明细信息中关联查询查商品信息。

SQL语句

主查询表:用户信息
关联查询:订单、订单明细、商品信息

[sql]
view plain
copy

SELECT
orders.*,
user.username,
user.sex ,
orderdetail.id orderdetail_id,
orderdetail.items_num,
orderdetail.items_id,
items.name items_name,
items.detail items_detail
FROM
orders,
USER,
orderdetail,
items
WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id AND items.id = orderdetail.items_id

查询结果



pojo定义

在User.java中创建映射的属性:集合List<Orders> orderlist;
在Orders中创建映射属性:集合List<Orderdetail> orderdetails;
在Orderdetail中创建商品属性:pojo Items items;







mapper.xml

[html]
view plain
copy

<!-- 一对多查询使用resultMap完成
查询用户及订单和订单明细,关联商品的信息
-->
<select id="findUserOrderDetail" resultMap="userOrderDetailResultMap">
SELECT
orders.*,
user.username,
user.sex ,
orderdetail.id orderdetail_id,
orderdetail.items_num,
orderdetail.items_id,
items.name items_name,
items.detail items_detail
FROM
orders,
USER,
orderdetail,
items
WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id AND items.id = orderdetail.items_id
</select>

resultMap定义

[html]
view plain
copy

<!-- 一对多查询,查询用户及订单明细和商品信息 -->
<resultMap type="user" id="userOrderDetailResultMap">
<!-- 用户信息映射 -->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<!-- 订单信息 -->
<collection property="orderlist" ofType="test.lx.mybatis.po.Orders">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!-- 订单明细映射 -->
<collection property="orderDetails" ofType="test.lx.mybatis.po.OrderDetail">
<!-- id: 关联信息订单明细的唯一标识
property: Orderdetail的属性名
-->
<id column="orderdetail_id" property="id"/>
<result column="items_num" property="itemsNum"/>
<result column="items_id" property="itemsId"/>
<!-- 商品信息 -->
<association property="items" javaType="test.lx.mybatis.po.Items">
<id column="item_id" property="id"/>
<result column="items_name" property="name"/>
<result column="items_detail" property="detail"/>
</association>
</collection>
</collection>
</resultMap>

mapper.java

[java]
view plain
copy

// 一对多查询,查询订单关联查询订单明细以及商品信息,使用resultMap
public List<User> findUserOrderDetail() throws Exception;

多对多查询

一对多是多对多的特例。

需求1:

查询显示字段:用户账号、用户名称、用户性别、商品名称、商品价格(最常见)

企业开发中常见明细列表,用户购买商品明细列表,

使用resultType将上边查询列映射到pojo输出。

需求2:

查询显示字段:用户账号、用户名称、购买商品数量、商品明细(鼠标移上显示明细)

使用resultMap将用户购买的商品明细列表映射到user对象中。
实现方法和一对多一样。

延迟加载

使用延迟加载的意义


在进行数据查询时,为了提高数据库查询性能,尽量使用单表查询,因为单表查询比多表关联查询速度快。

如果查询单表就可以满足需求,一开始先查询单表,当需要关联信息时,再关联查询。当需要关联信息时才进行查询就叫做延迟加载。mybatis中resultMap提供延迟加载功能,通过resultMap配置延迟加载。



在SqlMapConfig.xml中配置全局参数

[html]
view plain
copy

<!-- 全局配置参数 -->
<settings>
<!-- 延迟加载总开关 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 设置按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>

延迟加载实现

实现思路

需求:查询订单及用户信息,一对一查询
刚开始只查询订单信息,当需要用户信息时调用Orders类中的getUser()方法执行延迟加载,向数据库发出SQL。

mapper.xml

[html]
view plain
copy

<!-- 一对一查询延迟加载
开始只查询订单,对用户信息进行延迟加载
-->
<select id="findOrderUserListLazyLoading" resultMap="orderCustomLazyLoading">
SELECT
orders.*
FROM
orders
</select>

resultMap

[html]
view plain
copy

<!-- 一对一查询延迟加载的配置 -->
<resultMap type="orders" id="orderCustomLazyLoading">
<!-- 完成了订单信息的映射配置 -->
<!-- id:订单关联用户查询的唯一标识 -->
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!--
select:延迟加载执行的sql所在的statement的id,如果不在同一个namespace需要加namespace
sql:根据用户id查询用户信息 column:关联查询的列
property:将关联查询的用户信息设置到Orders的哪个属性 -->
<association property="user" select="test.lx.mybatis.mapper.UserMapper.findUserById" column="user_id">
</association>
</resultMap>

mapper.java

[java]
view plain
copy

// 一对一查询,查询订单延迟加载用户信息,使用resultMap
public List<Orders> findOrderUserListLazyLoading() throws Exception;

测试代码

[java]
view plain
copy

//一对一查询 延迟加载
@Test
public void testFindOrderUserListLazyLoading() throws Exception{
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建mapper代理对象
OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
// 调用方法
List<Orders> list = ordersMapperCustom.findOrderUserListLazyLoading();

//这里执行延迟加载,要发出SQL
User user = list.get(0).getUser();
System.out.println(user);
}



一对多查询延迟加载

一对多延迟加载的方法同一对一延迟加载,在collection标签中配置select内容。

resultType、resultMap、延迟加载使用场景总结

延迟加载:延迟加载实现的方法多种多样,在只查询单表就可以满足需求,为了提高数据库查询性能使用延迟加载,再查询关联信息。
注意:mybatis提供的延迟加载的功能用于Service。
resultType:
作用:将查询结果按照sql列名和pojo属性名的一致性映射到pojo中。
场合:常见一些明细记录的展示,将关联信息全部展示到页面上时,此时可直接使用resultType将每一条记录映射到pojo中,在前端页面遍历list(list中是pojo即可)
resultMap:使用association和collection完成一对一和一对多高级映射。
association:
作用:将关联查询信息映射到一个pojo类中。
场合:为了方便获取关联信息可以使用association将关联订单映射为pojo,比如:查询订单关联查询用户信息。
collection:
作用:将关联查询信息映射到一个list集合中。
场合:为了方便获取关联信息可以使用collection将关联信息映射到list集合中,比如:查询用户权限范围模块和功能,可以使用collection将模块和功能列表映射到list中。

查询缓存

缓存的意义

将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)去查询,从缓存中进行查询,从而提高查询效率,解决了高并发系统的性能问题。



mybatis持久层缓存

mybatis提供一级缓存和二级缓存



mybatis一级缓存是一个Sqlsession级别,SqlSession只能访问自己的一级缓存数据,二级缓存是跨SqlSession的,是mapper级别的缓存,对于mapper级别的缓存 不同的SqlSession是可以共享的。

一级缓存

原理



第一次发出一个查询sql,sql查询结果写入SqlSession一级缓存中,缓存使用的数据结构是一个map<key,value>
key: hashcode+sql+sql输入参数+sql输出参数 (作为SQL的唯一标识)
value: 用户信息。
同一个sqlSession再次发出相同的sql,就从缓存中取数据,不再查询数据库。如果两次中间出现commit操作(修改、添加、删除),此SqlSession中的一级缓存数据全部清空,下次再去缓存中就会查询不到数据再从数据库查询,从数据库查询到后再写入缓存。
每次查询都先从缓存进行查询。
注意:清空时会清空当前sqlsession缓存区域中的全部内容。

一级缓存配置

mybatis默认支持一级缓存不需要配置
注意:mybatis和Spring整合后进行mapper代理开发,不支持一级缓存,mybatis和Spring整合,Spring按照mapper的模板去生成mapper代理对象,模板中在最后统一关闭sqlsession。

一级缓存测试

[java]
view plain
copy

//一级缓存
@Test
public void testCache1() throws Exception {

SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

//第一次查询用户id为1的用户
User user = userMapper.findUserById(1);
User userX = userMapper.findUserById(2);
System.out.println(user);

//中间修改用户要清空缓存,目的防止查询出脏数据
/*user.setUsername("测试用户2");
userMapper.updateUser(user);
sqlSession.commit(); */

//第二次查询用户id为1的用户
User user2 = userMapper.findUserById(1);
User userX2 = userMapper.findUserById(2);
System.out.println(user2);

sqlSession.close();
}

测试可以发现,当前SQLSession只要执行任意一个commit(),id为1和2的用户都会在缓存中被清空,所以说,commit后会清空当前sqlsession缓存区域中的全部内容。

二级缓存

二级缓存原理



二级缓存的范围是mapper级别(mapper同一个命名空间),mapper以命名空间为单位创建缓存数据结构,结构为map<key,value>
每次查询先看是否开启二级缓存,如果开启先从二级缓存中数据结构中取缓存数据。
如果从二级缓存中没有取到,再从一级缓存中进行查找,如果一级缓存也没有,从数据库查询。

mybatis二级缓存配置

在核心配置文件SqlMapConfig.xml中全局设置中加入
<setting name="cacheEnabled" value="true"/>
cacheEnabled: 对此配置文件下的所有cache进行全局性开/关设置。允许值true/false,默认为true。
然后在Mapper的映射文件中添加一行:<cache/>, 表示此mapper开启二级缓存。

查询结果映射的pojo序列化

mybatis二级缓存需要将查询结果映射的pojo实现 java.io.serializable接口,如果不实现则抛出异常:org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException

二级缓存可以将内存中的数据写到硬盘,存在对象的序列和反序列化,所以要实现java.io.serializable接口。如果结果映射的pojo中还关联了别的pojo,那么它和它所关联的pojo也都要实现java.io.serializable接口。



二级缓存的禁用

对于变化频率较高的sql,需要禁用二级缓存:

在statement中设置useCache=false可以禁用当前select语句的二级缓存,即每次查询都会发出sql去查询,默认情况是true,即该sql使用二级缓存。

<select id="findOrderListResultMap" resultMap="ordersUserMap" useCache="false">

刷新缓存

如果SqlSession操作commit操作,对二级缓存进行刷新(全局清空)
设置与commit相关statement(insert,update,delete等标签)的flushCache属性是否刷新缓存,默认值是true,如果设置了为false,即使后台数据库发生了变化,只要缓存没有过期,也只会读取缓存中数据 就会获取不到最新数据。

测试代码

[java]
view plain
copy

//二级缓存的测试
@Test
public void testCache2() throws Exception {

SqlSession sqlSession1 = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
SqlSession sqlSession3 = sqlSessionFactory.openSession();
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);

//第一次查询用户id为1的用户
User user = userMapper1.findUserById(1);
System.out.println(user);
sqlSession1.close();

//中间修改用户要清空缓存,目的防止查询出脏数据
/*user.setUsername("测试用户2");
userMapper3.updateUser(user);
sqlSession3.commit();
sqlSession3.close();*/

//第二次查询用户id为1的用户
User user2 = userMapper2.findUserById(1);
System.out.println(user2);

sqlSession2.close();
}

mybatis自带的cache参数属性(了解)

mybatis的cache参数只适用于mybatis维护缓存。

flushInterval(刷新间隔)可以被设置为任意的正整数,而且它们代表一个合理的毫秒形式的时间段。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。

size(引用数目)可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的可用内存资源数目。默认值是1024。

readOnly(只读)属性可以被设置为true或false。只读的缓存会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。可读写的缓存会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。

如下例子:

<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>

这个更高级的配置创建了一个 FIFO 缓存,并每隔 60 秒刷新,存数结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此在不同线程中的调用者之间修改它们会导致冲突。可用的收回策略有, 默认的是 LRU:

LRU – 最近最少使用的:移除最长时间不被使用的对象。

FIFO – 先进先出:按对象进入缓存的顺序来移除它们。

SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。

WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。

mybatis和ehcache缓存框架整合

mybatis二级缓存通过ehcache维护缓存数据。

分布缓存

将缓存数据进行分布式管理



mybatis和ehcache思路

通过mybatis和ehcache框架进行整合,既可以将缓存数据的管理托管给ehcache。
在mybatis中提供了一个cache接口,只要实现cache接口就可以把缓存数据灵活的管理起来。



mybatis中的默认实现



下载和ehcache整合的jar包



ehcache对cache接口的实现类



在calsspath下配置ehcache.xml

[html]
view plain
copy

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!--diskStore:缓存数据持久化的目录 地址 -->
<diskStore path="/Users/liuxun/Desktop/ehcache" />
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
diskPersistent="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>

整合ehcache

在mapper.xml下添加ehcache配置

[html]
view plain
copy

<!-- 开启二级缓存 -->
<!-- 单位:毫秒 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="timeToIdleSeconds" value="12000"/>
<property name="timeToLiveSeconds" value="3600"/>
<!-- 同ehcache参数maxElementsInMemory -->
<property name="maxEntriesLocalHeap" value="1000"/>
<!-- 同ehcache参数maxElementsOnDisk -->
<property name="maxEntriesLocalDisk" value="10000000"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>



二级缓存的应用场景

对于查询频率高,变化频率低的数据建议使用二级缓存。
对于访问多的查询请求且用户对查询结果的实时性要求不高,此时可采用mybatis二级缓存技术降低数据库的访问量,提高访问速度,业务场景比如:耗时较高的统计分析sql、电话账单查询sql等。
实现方法如下:通过设置刷新时间间隔,由mybatis每隔一段时间自动清空缓存,根据数据变化频率设置缓存刷新时间间隔flushInterval,比如设置30分钟、60分钟、24小时等,根据需求而定。

mybatis局限性

mybatis二级缓存对细粒度的数据级别的缓存实现不好,比如如下需求:对商品信息进行缓存,由于商品信息查询访问量大,但是要求用户每次都能查询最新的商品信息,此时如果使用mybatis的二级缓存就无法实现当一个商品变化时只刷新该商品的缓存信息而不刷新其它商品的信息,因为mybaits的二级缓存区域以mapper为单位划分,当一个商品信息变化会将所有商品信息的缓存数据全部清空。解决此类问题需要在业务层根据需求对数据有针对性缓存。

项目代码

完整代码已经上传GitHub(https://github.com/LX1993728/mybatisDemo_2





OrdersMapperCustom.java

[java]
view plain
copy

package test.lx.mybatis.mapper;

import java.util.List;

import test.lx.mybatis.po.OrderCustom;
import test.lx.mybatis.po.Orders;
import test.lx.mybatis.po.User;

/**
* 订单自定义的mapper接口
*
* @author liuxun
*
*/
public interface OrdersMapperCustom {
// 一对一查询,查询订单关联查询用户,使用resultType
public List<OrderCustom> findOrderUserList() throws Exception;

// 一对一查询,查询订单关联查询用户,使用resultMap
public List<Orders> findOrderUserListResultMap() throws Exception;

// 一对一查询,查询订单延迟加载用户信息,使用resultMap
public List<Orders> findOrderUserListLazyLoading() throws Exception;

// 一对多查询,查询订单关联查询订单明细,使用resultMap
public List<Orders> findOrderAndOrderdetails() throws Exception;

// 一对多查询,查询订单关联查询订单明细以及商品信息,使用resultMap
public List<User> findUserOrderDetail() throws Exception;
}

OrdersMapperCustom.xml

[html]
view plain
copy

<?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="test.lx.mybatis.mapper.OrdersMapperCustom">

<!-- 一对一查询resultMap -->
<resultMap type="orders" id="ordersUserResultMap">
<!-- 完成了订单信息的映射配置 -->
<!-- id:订单关联用户查询的唯一标识 -->
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>

<!-- 下边完成关联信息的映射
association: 用于对关联信息映射到单个pojo
property: 要将关联信息映射到orders的哪个属性中
javaType: 关联信息映射到orders的属性类型,是user类型
-->
<association property="user" javaType="user">
<!-- id:关联信息的唯一标识 -->
<!-- property:要映射到所关联表中的哪个属性 -->
<id column="user_id" property="id"/>
<!-- result就是普通列的映射 -->
<result column="username" property="username"/>
<result column="sex" property="sex"/>
</association>
</resultMap>

<!-- 一对一查询延迟加载的配置 -->
<resultMap type="orders" id="orderCustomLazyLoading">
<!-- 完成了订单信息的映射配置 -->
<!-- id:订单关联用户查询的唯一标识 -->
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!--
select:延迟加载执行的sql所在的statement的id,如果不在同一个namespace需要加namespace
sql:根据用户id查询用户信息 column:关联查询的列
property:将关联查询的用户信息设置到Orders的哪个属性 -->
<association property="user" select="test.lx.mybatis.mapper.UserMapper.findUserById" column="user_id">
</association>
</resultMap>

<!-- 一对多,查询订单以及订单明细 -->
<resultMap type="orders" id="orderAndOrderDetails" extends="ordersUserResultMap">
<!-- 映射订单信息,和用户信息,这里使用继承 ordersUserResultMap-->

<!-- 映射订单明细信息
property: 要将关联信息映射到orders的哪个属性中
ofType: 集合中的pojo属性
-->
<collection property="orderDetails" ofType="test.lx.mybatis.po.OrderDetail">
<!-- id: 关联信息订单明细的唯一标识
property: Orderdetail的属性名
-->
<id column="orderdetail_id" property="id"/>
<result column="items_num" property="itemsNum"/>
<result column="items_id" property="itemsId"/>
</collection>
</resultMap>

<!-- 一对多查询,查询用户及订单明细和商品信息 -->
<resultMap type="user" id="userOrderDetailResultMap">
<!-- 用户信息映射 -->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<!-- 订单信息 -->
<collection property="orderlist" ofType="test.lx.mybatis.po.Orders">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!-- 订单明细映射 -->
<collection property="orderDetails" ofType="test.lx.mybatis.po.OrderDetail">
<!-- id: 关联信息订单明细的唯一标识
property: Orderdetail的属性名
-->
<id column="orderdetail_id" property="id"/>
<result column="items_num" property="itemsNum"/>
<result column="items_id" property="itemsId"/>
<!-- 商品信息 -->
<association property="items" javaType="test.lx.mybatis.po.Items">
<id column="item_id" property="id"/>
<result column="items_name" property="name"/>
<result column="items_detail" property="detail"/>
</association>
</collection>
</collection>
</resultMap>

<!-- 一对一查询使用resultType完成
查询订单关联查询用户信息
-->
<select id="findOrderUserList" resultType="orderCustom">
SELECT
orders.*, user.username, user.sex
FROM
orders,
user
WHERE
orders.user_id = user.id;
</select>

<!-- 一对一查询使用resultMap完成
查询订单关联查询用户信息
-->
<select id="findOrderUserListResultMap" resultMap="ordersUserResultMap">
SELECT
orders.*, user.username, user.sex
FROM
orders,
user
WHERE
orders.user_id = user.id;
</select>

<!-- 一对多查询使用resultMap完成
查询订单关联查询订单明细
-->
<select id="findOrderAndOrderdetails" resultMap="orderAndOrderDetails">
SELECT
orders.*,
user.username,
user.sex ,
orderdetail.id orderdetail_id,
orderdetail.items_num,
orderdetail.items_id
FROM
orders,
USER,
orderdetail
WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id
</select>

<!-- 一对多查询使用resultMap完成
查询用户及订单和订单明细,关联商品的信息
-->
<select id="findUserOrderDetail" resultMap="userOrderDetailResultMap">
SELECT
orders.*,
user.username,
user.sex ,
orderdetail.id orderdetail_id,
orderdetail.items_num,
orderdetail.items_id,
items.name items_name,
items.detail items_detail
FROM
orders,
USER,
orderdetail,
items
WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id AND items.id = orderdetail.items_id
</select>

<!-- 一对一查询延迟加载
开始只查询订单,对用户信息进行延迟加载
-->
<select id="findOrderUserListLazyLoading" resultMap="orderCustomLazyLoading">
SELECT
orders.*
FROM
orders
</select>

</mapper>

ehcache.xml

[html]
view plain
copy

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!--diskStore:缓存数据持久化的目录 地址 -->
<diskStore path="/Users/liuxun/Desktop/ehcache" />
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
diskPersistent="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>

UserMapper.xml

[html]
view plain
copy

<?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">
<!-- namespace命名空间,为了对SQL语句进行隔离,方便管理,mapper可开发dao方式,使用namespace有特殊作用
mapper代理开发时将namespace指定为mapper接口的全限定名 -->
<mapper namespace="test.lx.mybatis.mapper.UserMapper">
<!-- 在mapper.xml文件中配置很多的SQL语句,执行每个SQL语句时,封装为MappedStatement对象
mapper.xml以statement为单位管理SQL语句
-->
<!-- 开启二级缓存 -->
<!-- 单位:毫秒 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="timeToIdleSeconds" value="12000"/>
<property name="timeToLiveSeconds" value="3600"/>
<!-- 同ehcache参数maxElementsInMemory -->
<property name="maxEntriesLocalHeap" value="1000"/>
<!-- 同ehcache参数maxElementsOnDisk -->
<property name="maxEntriesLocalDisk" value="10000000"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
<!-- 将用户查询条件定义为SQL片段
建议对单表的查询条件单独抽取成SQL片段,提高公用性
注意:不要讲where标签放在SQL片段,因为where条件中可能有多个SQL片段进行结合
-->
<sql id="query_user_where">
<!-- 如果userQueryVo中传入查询条件,在进行SQL拼接 -->
<!-- test中userCustom.username表示从userQueryVo中读取属性值 -->
<if test="userCustom!=null">
<if test="userCustom.username!=null and userCustom.username.trim().length() > 0">
and username like '%${userCustom.username.trim()}%'
</if>
<if test="userCustom.sex!=null and userCustom.sex!=''">
and sex = #{userCustom.sex}
</if>
<!-- 根据id集合查询用户信息 -->
<!-- 最终拼接的效果:
SELECT id,username,birthday FROM USER WHERE username LIKE '%小明%' AND id IN (16,22,25)
collection: pojo中的表示集合的属性
open: 开始循环拼接的串
close: 结束循环拼接的串
item: 每次循环从集合中取到的对象
separator: 没两次循环中间拼接的串
-->
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open=" AND id IN (" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
<!--
SELECT id ,username ,birthday FROM USER WHERE username LIKE '%小明%' AND (id = 16 OR id = 22 OR id = 25)
<foreach collection="ids" open=" AND id IN (" close=")" item="id" separator=" OR ">
id=#{id}
</foreach>
-->
<!-- 还可以添加更多的查询条件 -->

</if>
</sql>

<!-- 定义resultMap,列名和属性名映射配置
id: mapper.xml中唯一标识
type: 最终要映射的pojo类型
-->
<resultMap id="userListResultMap" type="user">
<!-- 列名
id,username_,birthday_
id:要映射结果集的唯一标识,称为主键
column: 结果集的列名
property:type指定pojo中的某个属性
-->
<id column="id_" property="id" />
<!-- result就是普通列的映射配置 -->
<result column="username_" property="username"/>
<result column="birthday_" property="birthday"/>
</resultMap>

<!-- 根据id查询用户信息 -->
<!--
id: 唯一标识一个statement
#{}:表示一个占位符,如果#{} 中传入简单类型的参数,#{}中的名称随意
parameterType: 输入参数的类型,通过#{}接收parameterType输入的参数
resultType:输出结果类型,不管返回是多条还是单条,指定单条记录映射的pojo类型
-->
<select id="findUserById" parameterType="int" resultType="user">
SELECT * FROM USER WHERE id=#{id};
</select>

<!-- 根据用户名称查询用户信息,可能返回多条
${}:表示SQL的拼接,通过${}接收参数,将参数的内容不加任何修饰的拼接在SQL中
-->
<select id="findUserByName" parameterType="java.lang.String" resultType="test.lx.mybatis.po.User">
select * from user where username like '%${value}%'
</select>

<!-- <select id="findUserByName" parameterType="java.lang.String" resultType="test.lx.mybatis.po.User">
select * from user where username like #{username}
</select> -->

<!-- 自定义查询条件查询用户信息
parameterType: 指定包装类型
%${userCustom.username}%: userCustom是userQueryVo中的属性,通过OGNL获取属性的值
-->
<select id="findUserList" parameterType="userQueryVo" resultType="user">
select * from user
<!-- where标签相当于where关键字,可以自动除去第一个and -->
<where>
<!-- 引用sql片段,如果sql片段和引用处不在同一个mapper 必须在前边加namespace. -->
<include refid="query_user_where"></include>
<!-- 下边还有很多其它的条件 -->
<!-- <include refid="其它的sql片段"></include> -->
</where>
</select>

<!-- 使用resultMap作为结果映射
resultMap: 如果引用resultMap的位置和resultMap的定义在同一个mapper.xml中,
直接使用resultMap的id,如果不在同一个mapper.xml中,要在引用resultMap的id前边加namespace
-->
<select id="findUserListResultMap" parameterType="userQueryVo" resultMap="userListResultMap">
select id id_,username username_,birthday birthday_ from user where username like '%${userCustom.username}%'
</select>

<!-- 输出简单类型
功能:自定义查询条件,返回查询记录个数,通常用于实现查询分页
-->
<select id="findUserCount" parameterType="userQueryVo" resultType="int">
select count(*) from user
<!-- where标签相当于where关键字,可以自动除去第一个and -->
<where>
<!-- 引用sql片段,如果sql片段和引用处不在同一个mapper 必须在前边加namespace. -->
<include refid="query_user_where"></include>
<!-- 下边还有很多其它的条件 -->
<!-- <include refid="其它的sql片段"></include> -->
</where>
</select>

<!-- 添加用户
parameterType:输入参数的类型,User对象包括username,birthday,sex,address
#{}接收pojo数据,可以使用OGNL解析出pojo的属性值
#{username}表示从parameterType中获取pojo的属性值
<selectKey>:用于进行主键返回,定义了主键值的SQL
order:设置selectKey标签中SQL的执行顺序,相对于insert语句而言
keyProperty: 将主键设置到哪个属性上
resultType:select LAST_INSERT_ID()的结果类型
-->
<insert id="insertUser" parameterType="test.lx.mybatis.po.User">
<selectKey keyProperty="id" order="AFTER" resultType="int">
select LAST_INSERT_ID()
</selectKey>
INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
</insert>

<!-- mysql的uuid()函数生成主键 -->
<!-- <insert id="insertUser" parameterType="test.lx.mybatis.po.User">
<selectKey keyProperty="id" order="BEFORE" resultType="string">
select uuid()
</selectKey>
INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
</insert> -->

<!-- oracle
在执行insert之前执行select 序列.nextval() from dual取出序列最大值,将值设置到user对象的id属性中
-->
<!-- <insert id="insertUser" parameterType="test.lx.mybatis.po.User">
<selectKey keyProperty="id" order="BEFORE" resultType="int">
select 序列.nextval() from dual
</selectKey>
INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
</insert> -->

<!-- 用户删除 -->
<delete id="deleteUser" parameterType="int" >
delete from user where id=#{id}
</delete>
<!-- 用户更新
要求:传入的user对象包括id属性值
-->
<update id="updateUser" parameterType="test.lx.mybatis.po.User">
update user set username = #{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>
</mapper>

SqlMapConfig.xml

[html]
view plain
copy

<?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文件
在properties标签中配置属性值
-->
<properties resource="db.properties">
<!-- <property name="" value=""/> -->
</properties>

<!-- 全局配置参数 -->
<settings>
<!-- 延迟加载总开关 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 设置按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 定义别名 -->
<typeAliases>
<!--
单个别名定义
alias:别名, type:别名映射类型
<typeAlias type="test.lx.mybatis.po.User" alias="user"/>
-->
<!-- 批量别名定义
指定包路径,自动扫描包内的pojo,定义别名,别名默认为类名(首字母小写或大写)
-->
<package name="test.lx.mybatis.po"/>
</typeAliases>

<!-- 和Spring整合后environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<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>

<!-- 加載mapper映射
如果和Spring整合后,可以使用整合包中的mapper扫描器,到那时此处的mapper就不用配置了
-->
<mappers>
<!-- 通过resource映入mapper的映射文件 -->
<mapper resource="sqlmap/User.xml" />
<!-- <mapper resource="test/lx/mybatis/mapper/UserMapper.xml"/> -->
<!-- 通过class引用mapper接口
class:配置mapper接口的全限定名
要求:需要mapper.xml和mapper.java同名并且在同一目录中
-->
<!-- <mapper class="test.lx.mybatis.mapper.UserMapper"/> -->
<!-- 批量mapper配置
通过package进行自动扫描包下边的mapper接口
要求:需要mapper.xml和mapper.java同名并在同一目录中
-->
<package name="test.lx.mybatis.mapper"/>
</mappers>
</configuration>

mybatis和Spring的整合

mybatis和Spring整合的思路

1.让Spring管理SqlSessionFactory
2.让Spring管理mapper对象和DAO
使用Spring和mybatis整合开发mapper代理对象以及原始Dao接口
自动开启事务,自动关闭sqlSession
3.让Spring管理数据源(数据库连接池)

创建整合工程



加入的jar包

1.mybatis3.2.7自身的jar包
2.数据库驱动包
3.spring3.2.0
4.spring和mybatis整合包
从mybatis的官方下载Spring和mybatis整合包



log4j.properties(略)

SqlMapConfig.xml

mybatis配置文件:别名、settings、数据源都不在这里进行配置

applicationContext.xml

1.数据源(dbcp连接池)
2.SqlSessionFactory
2.mapper或DAO

整合开发原始Dao接口

配置SqlSessionFactory

在applicationContext.xml中配置SqlSessionFactory

[html]
view plain
copy

<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
</bean>

开发原始DAO

[java]
view plain
copy

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

public User findUserById(int id) throws Exception {
// 创建SqlSession
SqlSession sqlSession = this.getSqlSession();

// 根据id查询用户信息
User user = sqlSession.selectOne("test.findUserById", id);
return user;
}
}

配置原始DAO

[html]
view plain
copy

<!-- 配置dao -->
<bean id="userDao" class="test.lx.mybatis.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

测试原始DAO接口

[java]
view plain
copy

public class UserDaoImplTest {
// 会话工厂
private ApplicationContext applicationContext;

//创建工厂
@Before
public void init() throws IOException{
// 创建Spring容器
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
}

@Test
public void testFindUserById() throws Exception{
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = userDao.findUserById(1);
System.out.println(user);
}

}

整合开发mapper代理方法

开发mapper.xml和mapper.java



使用MapperFactoryBean

[html]
view plain
copy

<!-- 配置mapper -->
<!-- MapperFactoryBean:用于生成mapper代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="test.lx.mybatis.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

使用此方法对每个mapper都需要配置,比较繁琐

使用MapperScannerConfigurer(扫描mapper)

[html]
view plain
copy

<!--
MapperScannerConfigurer: mapper扫描器,将包下的mapper接口自动创建代理对象,
自动创建到Spring容器中,bean的id是mapper的类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描包的路径
如果要扫描多个包,中间使用半角逗号 , 隔开
-->
<property name="basePackage" value="test.lx.mybatis.mapper"/>
<!-- 使用sqlSessionFactoryBeanName -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

使用扫描器自动扫描mapper,生成代理对象,比较方便。

测试mapper接口

[java]
view plain
copy

public class UserMapperTest {

// 会话工厂
private ApplicationContext applicationContext;

//创建工厂
@Before
public void init() throws IOException{
// 创建Spring容器
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
}

@Test
public void testFindUserById() throws Exception {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}

}

mybatis逆向工程(Mybatis Generator)

什么是mybatis的逆向工程

mybatis官方为了提高开发效率,提供自动对表单生成SQL,包括:mapper.xml,mapper.java, 表名.java(po类)



在企业开发中通常是在设计阶段对表进行设计、创建。
在开发阶段根据表结构创建对应的po类。
mybatis逆向工程的方向:由数据表—>java代码

逆向工程使用配置

运行逆向工程 方法:



为了避免插件的局限性,还是推荐使用Java程序生成
逆向工程运行所需要的jar包



数据库驱动包。

xml配置

需要使用配置的地方
需要注意的是:涉及到路径时,一定要写绝对路径,相对路径有时是不起作用的。
1.连接数据库的地址和驱动

[html]
view plain
copy

<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"
password="root">
</jdbcConnection>

2.需要配置PO类的包路径

[html]
view plain
copy

<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="test.lx.mybatis.po"
targetProject="/Users/liuxun/Workspaces/MyEclipse_2017_CI/Mybatis_generatorSqlMapCustom/src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>

3.配置mapper包的路径

[html]
view plain
copy

<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="test.lx.mybatis.mapper"
targetProject="/Users/liuxun/Workspaces/MyEclipse_2017_CI/Mybatis_generatorSqlMapCustom/src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="test.lx.mybatis.mapper"
targetProject="/Users/liuxun/Workspaces/MyEclipse_2017_CI/Mybatis_generatorSqlMapCustom/src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>

4.指定数据表

[html]
view plain
copy

<!-- 指定数据库表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail" ></table>

xml配置使用详解

[html]
view plain
copy

<?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>
<!-- 可以用于加载配置项或者配置文件,在整个配置文件中就可以使用${propertyKey}的方式来引用配置项
resource:配置资源加载地址,使用resource,MBG从classpath开始找,比如com/myproject/generatorConfig.properties
url:配置资源加载地质,使用URL的方式,比如file:///C:/myfolder/generatorConfig.properties.
注意,两个属性只能选址一个;

另外,如果使用了mybatis-generator-maven-plugin,那么在pom.xml中定义的properties都可以直接在generatorConfig.xml中使用
<properties resource="" url="" />
-->

<!-- 在MBG工作的时候,需要额外加载的依赖包
location属性指明加载jar/zip包的全路径
<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />
-->

<!--
context:生成一组对象的环境
id:必选,上下文id,用于在生成错误时提示
defaultModelType:指定生成对象的样式
1,conditional:类似hierarchical;
2,flat:所有内容(主键,blob)等全部生成在一个对象中;
3,hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class)
targetRuntime:
1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample;
2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample;
introspectedColumnImpl:类全限定名,用于扩展MBG
-->
<context id="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" >

<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖
-->
<property name="autoDelimitKeywords" value="false"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>

<!-- 必须要有的,使用这个配置链接数据库
@TODO:是否可以扩展
-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql:///pss" userId="root" password="admin">
<!-- 这里面可以设置property属性,每一个property属性都设置到配置的Driver上 -->
</jdbcConnection>

<!-- java类型处理器
用于处理DB中的类型到Java中的类型,默认使用JavaTypeResolverDefaultImpl;
注意一点,默认会先尝试使用Integer,Long,Short等来对应DECIMAL和 NUMERIC数据类型;
-->
<javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
<!--
true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型
false:默认,
scale>0;length>18:使用BigDecimal;
scale=0;length[10,18]:使用Long;
scale=0;length[5,9]:使用Integer;
scale=0;length<5:使用Short;
-->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>

<!-- java模型创建器,是必须要的元素
负责:1,key类(见context的defaultModelType);2,java类;3,查询类
targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制;
targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录
-->
<javaModelGenerator targetPackage="com._520it.mybatis.domain" targetProject="src/main/java">
<!-- for MyBatis3/MyBatis3Simple
自动为每一个生成的类创建一个构造方法,构造方法包含了所有的field;而不是使用setter;
-->
<property name="constructorBased" value="false"/>

<!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
<property name="enableSubPackages" value="true"/>

<!-- for MyBatis3 / MyBatis3Simple
是否创建一个不可变的类,如果为true,
那么MBG会创建一个没有setter方法的类,取而代之的是类似constructorBased的类
-->
<property name="immutable" value="false"/>

<!-- 设置一个根对象,
如果设置了这个根对象,那么生成的keyClass或者recordClass会继承这个类;在Table的rootClass属性中可以覆盖该选项
注意:如果在key class或者record class中有root class相同的属性,MBG就不会重新生成这些属性了,包括:
1,属性名相同,类型相同,有相同的getter/setter方法;
-->
<property name="rootClass" value="com._520it.mybatis.domain.BaseDomain"/>

<!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>

<!-- 生成SQL map的XML文件生成器,
注意,在Mybatis3之后,我们可以使用mapper.xml文件+Mapper接口(或者不用mapper接口),
或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的话,这个元素就必须配置
targetPackage/targetProject:同javaModelGenerator
-->
<sqlMapGenerator targetPackage="com._520it.mybatis.mapper" targetProject="src/main/resources">
<!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false --> <
20000
/span>
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>

<!-- 对于mybatis来说,即生成Mapper接口,注意,如果没有配置该元素,那么默认不会生成Mapper接口
targetPackage/targetProject:同javaModelGenerator
type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):
1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),不会生成对应的XML;
2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中;
3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML;
注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
-->
<javaClientGenerator targetPackage="com._520it.mybatis.mapper" type="ANNOTATEDMAPPER" targetProject="src/main/java">
<!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
<property name="enableSubPackages" value="true"/>

<!-- 可以为所有生成的接口添加一个父接口,但是MBG只负责生成,不负责检查
<property name="rootInterface" value=""/>
-->
</javaClientGenerator>

<!-- 选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
选择的table会生成一下文件:
1,SQL map文件
2,生成一个主键类;
3,除了BLOB和主键的其他字段的类;
4,包含BLOB的类;
5,一个用户生成动态查询的条件类(selectByExample, deleteByExample),可选;
6,Mapper接口(可选)

tableName(必要):要生成对象的表名;
注意:大小写敏感问题。正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下,MBG会
根据设置的schema,catalog或tablename去查询数据表,按照下面的流程:
1,如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询;
2,否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找;
3,否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找;
4,否则,使用指定的大小写格式查询;
另外的,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名;
这个时候,请设置delimitIdentifiers="true"即可保留大小写格式;

可选:
1,schema:数据库的schema;
2,catalog:数据库的catalog;
3,alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName
4,domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面;
5,enableInsert(默认true):指定是否生成insert语句;
6,enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get);
7,enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句;
8,enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update);
9,enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete);
10,enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句;
11,enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询);
12,enableUpdateByExample(默认true):MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性);
13,modelType:参考context元素的defaultModelType,相当于覆盖;
14,delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性)
15,delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来。默认为false,delimitIdentifiers参考context的属性

注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写;
-->
<table tableName="userinfo" >

<!-- 参考 javaModelGenerator 的 constructorBased属性-->
<property name="constructorBased" value="false"/>

<!-- 默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema; -->
<property name="ignoreQualifiersAtRuntime" value="false"/>

<!-- 参考 javaModelGenerator 的 immutable 属性 -->
<property name="immutable" value="false"/>

<!-- 指定是否只生成domain类,如果设置为true,只生成domain类,如果还配置了sqlMapGenerator,那么在mapper XML文件中,只生成resultMap元素 -->
<property name="modelOnly" value="false"/>

<!-- 参考 javaModelGenerator 的 rootClass 属性
<property name="rootClass" value=""/>
-->

<!-- 参考javaClientGenerator 的 rootInterface 属性
<property name="rootInterface" value=""/>
-->

<!-- 如果设置了runtimeCatalog,那么在生成的SQL中,使用该指定的catalog,而不是table元素上的catalog
<property name="runtimeCatalog" value=""/>
-->

<!-- 如果设置了runtimeSchema,那么在生成的SQL中,使用该指定的schema,而不是table元素上的schema
<property name="runtimeSchema" value=""/>
-->

<!-- 如果设置了runtimeTableName,那么在生成的SQL中,使用该指定的tablename,而不是table元素上的tablename
<property name="runtimeTableName" value=""/>
-->

<!-- 注意,该属性只针对MyBatis3Simple有用;
如果选择的runtime是MyBatis3Simple,那么会生成一个SelectAll方法,如果指定了selectAllOrderByClause,那么会在该SQL中添加指定的这个order条件;
-->
<property name="selectAllOrderByClause" value="age desc,username asc"/>

<!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是bornDate -->
<property name="useActualColumnNames" value="false"/>

<!-- generatedKey用于生成生成主键的方法,
如果设置了该元素,MBG会在生成的<insert>元素中生成一条正确的<selectKey>元素,该元素可选
column:主键的列名;
sqlStatement:要生成的selectKey语句,有以下可选项:
Cloudscape:相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL()
DB2 :相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL()
DB2_MF :相当于selectKey的SQL为:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
Derby :相当于selectKey的SQL为:VALUES IDENTITY_VAL_LOCAL()
HSQLDB :相当于selectKey的SQL为:CALL IDENTITY()
Informix :相当于selectKey的SQL为:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
MySql :相当于selectKey的SQL为:SELECT LAST_INSERT_ID()
SqlServer :相当于selectKey的SQL为:SELECT SCOPE_IDENTITY()
SYBASE :相当于selectKey的SQL为:SELECT @@IDENTITY
JDBC :相当于在生成的insert元素上添加useGeneratedKeys="true"和keyProperty属性
<generatedKey column="" sqlStatement=""/>
-->

<!--
该元素会在根据表中列名计算对象属性名之前先重命名列名,非常适合用于表中的列都有公用的前缀字符串的时候,
比如列名为:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等;
那么就可以设置searchString为"^CUST_",并使用空白替换,那么生成的Customer对象中的属性名称就不是
custId,custName等,而是先被替换为ID,NAME,EMAIL,然后变成属性:id,name,email;

注意,MBG是使用java.util.regex.Matcher.replaceAll来替换searchString和replaceString的,
如果使用了columnOverride元素,该属性无效;

<columnRenamingRule searchString="" replaceString=""/>
-->

<!-- 用来修改表中某个列的属性,MBG会使用修改后的列来生成domain的属性;
column:要重新设置的列名;
注意,一个table元素中可以有多个columnOverride元素哈~
-->
<columnOverride column="username">
<!-- 使用property属性来指定列要生成的属性名称 -->
<property name="property" value="userName"/>

<!-- javaType用于指定生成的domain的属性类型,使用类型的全限定名
<property name="javaType" value=""/>
-->

<!-- jdbcType用于指定该列的JDBC类型
<property name="jdbcType" value=""/>
-->

<!-- typeHandler 用于指定该列使用到的TypeHandler,如果要指定,配置类型处理器的全限定名
注意,mybatis中,不会生成到mybatis-config.xml中的typeHandler
只会生成类似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的参数描述
<property name="jdbcType" value=""/>
-->

<!-- 参考table元素的delimitAllColumns配置,默认为false
<property name="delimitedColumnName" value=""/>
-->
</columnOverride>

<!-- ignoreColumn设置一个MGB忽略的列,如果设置了改列,那么在生成的domain中,生成的SQL中,都不会有该列出现
column:指定要忽略的列的名字;
delimitedColumnName:参考table元素的delimitAllColumns配置,默认为false

注意,一个table元素中可以有多个ignoreColumn元素
<ignoreColumn column="deptId" delimitedColumnName=""/>
-->
</table>

</context>

</generatorConfiguration>

java程序

通过Java程序生成mapper类、po类

[java]
view plain
copy

public class GeneratorSqlmap {

public void generator() throws Exception{

List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("generatorConfig.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();
}

}

}

使用逆向工程生成代码

第一步:配置generatorConfig.xml



第二步配置执行Java程序

执行Java程序后,所生成的代码已经在当前项目中



第三步:将生成的代码拷贝到项目工程中

mybatis逆向工程源代码

此完整代码已上传GitHub(https://github.com/LX1993728/Mybatis_generatorSqlMapCustom
generatorConfig.xml

[html]
view plain
copy

<?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/mybatis" 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="test.lx.mybatis.po"
targetProject="/Users/liuxun/Workspaces/MyEclipse_2017_CI/Mybatis_generatorSqlMapCustom/src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="test.lx.mybatis.mapper"
targetProject="/Users/liuxun/Workspaces/MyEclipse_2017_CI/Mybatis_generatorSqlMapCustom/src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="test.lx.mybatis.mapper"
targetProject="/Users/liuxun/Workspaces/MyEclipse_2017_CI/Mybatis_generatorSqlMapCustom/src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail" ></table>
<!-- <table schema="" tableName="sys_user"></table>
<table schema="" tableName="sys_role"></table>
<table schema="" tableName="sys_permission"></table>
<table schema="" tableName="sys_user_role"></table>
<table schema="" tableName="sys_role_permission"></table> -->

<!-- 有些表的字段需要指定java类型
<table schema="" tableName="">
<columnOverride column="" javaType="" />
</table> -->
</context>
</generatorConfiguration>

GeneratorSqlMap.java

[java]
view plain
copy

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlmap {

public void generator() throws Exception{

List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("generatorConfig.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();
}

}

}

Spring与mybatis整合源代码

代码已上传GitHub (https://github.com/LX1993728/spring_mybatis)





UserDao(原始Dao接口)

[java]
view plain
copy

package test.lx.mybatis.dao;

import java.util.List;

import test.lx.mybatis.po.User;

/**
* 用户DAO
*
* @author lx
*
*/
public interface UserDao {
// 根据id查询用户信息
public User findUserById(int id) throws Exception;

}

UserDaoImpl(原始DAO实现类 继承自SqlSessionDaoSupport)

[java]
view plain
copy

package test.lx.mybatis.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import test.lx.mybatis.po.User;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

public User findUserById(int id) throws Exception {
// 创建SqlSession
SqlSession sqlSession = this.getSqlSession();

// 根据id查询用户信息
User user = sqlSession.selectOne("test.findUserById", id);
return user;
}
}

DAO—mapper代理实现(Java代码不做任何改变 还是原来的mapper代理实现 只是需要配置一下而已)
SqlMapConfig.xml

[html]
view plain
copy

<?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>
<!-- 定义别名 -->
<typeAliases>
<!-- 批量别名定义 指定包路径,自动扫描包内的pojo,定义别名,别名默认为类名(首字母小写或大写) -->
<package name="test.lx.mybatis.po" />
</typeAliases>

<mappers>
<!-- 加载原始Dao使用的user.xml -->
<mapper resource="sqlmap/User.xml" />
<package name="test.lx.mybatis.mapper" />
</mappers>
</configuration>

applicationContext.xml

[html]
view plain
copy

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>

<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
</bean>

<!-- 配置dao -->
<bean id="userDao" class="test.lx.mybatis.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

<!-- 配置mapper -->
<!-- MapperFactoryBean:用于生成mapper代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="test.lx.mybatis.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

<!--
MapperScannerConfigurer: mapper扫描器,将包下的mapper接口自动创建代理对象,
自动创建到Spring容器中,bean的id是mapper的类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描包的路径
如果要扫描多个包,中间使用半角逗号 , 隔开
-->
<property name="basePackage" value="test.lx.mybatis.mapper"/>
<!-- 使用sqlSessionFactoryBeanName -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>

UserDaoImplTest(测试原始Dao代码)

[java]
view plain
copy

package test.lx.mybatis.dao;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.lx.mybatis.po.User;

public class UserDaoImplTest {
// 会话工厂
private ApplicationContext applicationContext;

//创建工厂
@Before
public void init() throws IOException{
// 创建Spring容器
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
}

@Test
public void testFindUserById() throws Exception{
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = userDao.findUserById(1);
System.out.println(user);
}

}

UserMapperTest(测试 mapper代理实现DAO接口的代码)

[java]
view plain
copy

package test.lx.mybatis.mapper;

import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.lx.mybatis.po.User;

public class UserMapperTest {

// 会话工厂
private ApplicationContext applicationContext;

//创建工厂
@Before
public void init() throws IOException{
// 创建Spring容器
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
}

@Test
public void testFindUserById() throws Exception {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}

}

ItemsMapperTest(*********测试拷贝逆向工程生成的代码)

[java]
view plain
copy

package test.lx.mybatis.mapper;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.lx.mybatis.po.Items;
import test.lx.mybatis.po.ItemsExample;

/**
* 切记:
* 不管是查询还是更新,只要涉及到多条记录 不带withBlobs后缀的方法 默认都不会对大文本字段进行操作
* 接口方法名中包含Selective的 表示有选择性的进行操作(只查询、更新、添加为参数复制过的属性对应的字段)
* 接口方法名中包含Example的 表示可以带有条件筛选
*
* @author liuxun
*
*/
public class ItemsMapperTest {
private ApplicationContext applicationContext;

private ItemsMapper itemsMapper;

@Before
public void setUp() throws Exception {
// 创建Spring容器
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
}

// 自定义条件筛选数量查询
@Test
public void testCountByExample() {
ItemsExample itemsExample = new ItemsExample();
ItemsExample.Criteria criteria = itemsExample.createCriteria();
criteria.andPriceBetween(300.f, 10000.f);
int count = itemsMapper.countByExample(itemsExample);
System.out.println(count);
}

// 自定义条件删除
@Test
public void testDeleteByExample() {
ItemsExample itemsExample = new ItemsExample();
ItemsExample.Criteria criteria = itemsExample.createCriteria();
criteria.andNameLike("%冰箱%"); // 使用like相关属性时 参数外要包括 %%
itemsMapper.deleteByExample(itemsExample);
}

// 根据主键进行删除
@Test
public void testDeleteByPrimaryKey() {
itemsMapper.deleteByPrimaryKey(6);
}

// 表示插入全部字段,若某字段对应属性没有复制,默认插为NULL(自增主键例外)
@Test
public void testInsert() {
Items items = new Items();
items.setName("电视机");
items.setPrice(3000.f);
items.setDetail("乐视高清");

itemsMapper.insert(items);
}

// 选择性插入,插入记录时只对赋值属性对应的字段进行插入
@Test
public void testInsertSelective() {
Items items = new Items();
items.setName("电冰箱");
items.setPrice(2500.f);
items.setDetail("三年包换");

itemsMapper.insertSelective(items);
}

// 自定义条件查询多条记录,包含大文本字段
@Test
public void testSelectByExampleWithBLOBs() {
ItemsExample itemsExample = new ItemsExample();
ItemsExample.Criteria criteria = itemsExample.createCriteria();
criteria.andNameIsNotNull();
List<Items> list = itemsMapper.selectByExampleWithBLOBs(itemsExample);
for (Items items : list) {
System.out.println(items.getDetail());
}
}

// 自定义条件查询多条记录,不对大文本字段进行查询
@Test
public void testSelectByExample() {
ItemsExample itemsExample = new ItemsExample();
ItemsExample.Criteria criteria = itemsExample.createCriteria();
criteria.andNameIsNotNull();
List<Items> list = itemsMapper.selectByExample(itemsExample);
for (Items items : list) {
System.out.println(items.getDetail()); // 大文本字段值为null
}

}

// 按照主键值进行查询单条记录
@Test
public void testSelectByPrimaryKey() {
Items items = itemsMapper.selectByPrimaryKey(1);
System.out.println(items.getDetail());
}

// 自定义条件更新(为POJO赋值过的属性对应的字段),不对PO类中的大文本字段进行更新
// 如果PO类对象中的一些属性未赋值,不做任何改变,只更新赋值过的属性 即有选择性的更新
@Test
public void testUpdateByExampleSelective() {
// 此处方法名后缀Selective:表示只对参数record中设置过的属性对应的字段进行更新 没有设置过的不做任何改变
// record:封装更新后的结果值
// example: 封装 筛选更新记录条件
ItemsExample example = new ItemsExample();
ItemsExample.Criteria criteria = example.createCriteria();
Items record = new Items();
record.setPrice(2500.f);
criteria.andNameLike("%机%");
itemsMapper.updateByExampleSelective(record, example);
}

// 根据外键强制全部更新数据(没有赋值的映射为NULL) 包含大文本字段
@Test
public void testUpdateByExampleWithBLOBs() {

}

// 根据外键强制全部更新数据(没有赋值的映射为NULL) 不包含大文本字段
@Test
public void testUpdateByExample() {

}

// 根据外键有选择性的更新数据 不包含大文本字段 必须为参数items设置主键值
@Test
public void testUpdateByPrimaryKeySelective() {

}
// 根据外键全部更新数据(没有赋值的映射为NULL) 包含大文本字段 必须为参数items设置主键值
@Test
public void testUpdateByPrimaryKeyWithBLOBs() {

}
// 根据外键有全部更新数据(没有赋值的映射为NULL) 不包含大文本字段 必须为参数items设置主键值
@Test
public void testUpdateByPrimaryKey() {

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息