1、输入映射和输出映射
Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心。
Ⅰ、parameterType(输入类型)
(1)传递简单类型:参考笔记一
(2)传递pojo对象:Mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称。(参考笔记一)
(3)传递pojo包装对象:开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
//实现根据用户名查询用户信息,查询条件放到QueryVo的user属性中
public class QueryVo {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
SQL语句:
SELECT * FROM user where username like '%刘%';
Mapper文件:
<!-- 使用包装类型查询用户,使用ognl从对象中取属性值,如果是包装对象可以使用.操作符来取内容部的属性 -->
<select id="findUserByQueryVo" parameterType="queryvo" resultType="user">
SELECT * FROM user where username like '%${user.username}%'
</select>
接口:
测试方法:
@Test
public void testFindUserByQueryVo() throws Exception {
SqlSession sqlSession = sessionFactory.openSession();
//获得mapper的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//创建QueryVo对象
QueryVo queryVo = new QueryVo();
//创建user对象
User user = new User();
user.setUsername("刘");
queryVo.setUser(user);
//根据queryvo查询用户
List<User> list = userMapper.findUserByQueryVo(queryVo);
System.out.println(list);
sqlSession.close();
}
Ⅱ、resultType(输出类型)
(1)输出简单类型
参考getnow输出日期类型,看下边的例子输出整型:
Mapper.xml文件:
<!-- 获取用户列表总数 -->
<selectid="findUserCount" parameterType="user" resultType="int">
select count(1) from user
</select>
Mapper接口:
public int findUserCount(User user) throws Exception;
测试代码:
Public void testFindUserCount() throws Exception{
//获取session
SqlSession session = sqlSessionFactory.openSession();
//获取mapper接口实例
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = new User();
user.setUsername("管理员");
//传递Hashmap对象查询用户列表
intcount = userMapper.findUserCount(user);
//关闭session
session.close();
}
输出简单类型必须查询出来的结果集有一条记录,最终将第一个字段的值转换为输出类型。
使用session的selectOne可查询单条记录。
(2)输出pojo对象:参考笔记一
(3)输出pojo列表:参考笔记一
Ⅲ、resultMap
resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。
如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系,resultMap实质上还需要将查询结果映射到pojo对象中。
resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
Mapper.xml定义:
使用resultMap指定上边定义的personmap。
定义resultMap:由于上边的mapper.xml中sql查询列和Users.java类属性不一致,需要定义resultMap:userListResultMap将sql查询列和Users.java类属性对应起来。
Mapper接口定义:
public List<User> findUserListResultMap(QueryVo queryVo) throws Exception;
2、动态SQL(通过MyBatis提供的各种标签方法实现动态拼接sql)
Ⅰ、If
<!-- 传递pojo综合查询用户信息 -->
<select id="findUserList" parameterType="user" resultType="user">
select * from user
where 1=1
<if test = " id!=null ">
and id=#{id}
</if>
<!--注意要做不等于空字符串校验-->
<if test = " username!=null and username!='' ">
and username like '%${username}%'
</if>
</select>
Ⅱ、Where(<where />可以自动处理第一个and)
上边的sql也可以改为:
<select id="findUserList" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</where>
</select>
Ⅲ、Foreach
传入多个id查询用户信息,需要向Sql传递数组或List,MyBatis使用foreach解析,用下边两个sql实现:
SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16);
SELECT * FROM USERS WHERE username LIKE '%张%' id IN (10,89,16);
在pojo中定义list属性ids存储多个用户id,并添加getter/setter方法:
Mapper.xml:
<if test="ids!=null and ids.size>0">
<foreach collection="ids" open=" and id in("close=")" item="id" separator=",">
#{id}
</foreach>
</if>
测试代码:
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);//查询id为1的用户
ids.add(10); //查询id为10的用户
queryVo.setIds(ids);
List<User> list = userMapper.findUserList(queryVo);
Ⅳ、SQL片段
Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的,如下:
<!-- 传递pojo综合查询用户信息 -->
<select id="findUserList" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</where>
</select>
将where条件抽取出来:
<sql id="query_user_where">
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</sql>
使用include引用:
<select id="findUserList" parameterType="user" resultType="user">
select * from user
<where>
<include refid="query_user_where"/>
</where>
</select>
注意:如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,如下:
<include refid="namespace.sql片段”/>
3、关联查询
Ⅰ、一对一查询
案例:查询所有订单信息,关联查询下单用户信息。
注意:因为一个订单信息只会是一个人下的订单,所以从查询订单信息出发关联查询用户信息为一对一查询。如果从用户信息出发查询用户下的订单信息则为一对多查询,因为一个用户可以下多个订单。
实现方案一:
使用resultType,定义订单信息po类,此po类中包括了订单信息和用户信息:
Sql语句:
SELECT
orders.*,
user.username,
userss.address
FROM
orders,
user
WHERE orders.user_id = user.id
定义po类:
Po类中应该包括上边sql查询出来的所有字段,如下:
//OrdersCustom类继承Orders类后OrdersCustom类包括了Orders类的所有字段,只需要定义用户的信息字段即可。
public class OrdersCustom extends Orders {
private String username;// 用户名称
private String address;// 用户地址
get/set。。。。
}
Mapper.xml:
<!-- 查询所有订单信息 -->
<select id="findOrdersList" resultType="mybatis.po.OrdersCustom">
SELECT
orders.*,
user.username,
user.address
FROM
orders, user
WHERE orders.user_id = user.id
</select>
Mapperr接口:
public List<OrdersCustom> findOrdersList() throws Exception;
测试类:
public void testfindOrdersList() throws Exception{
//获取session
SqlSession session = sqlSessionFactory.openSession();
//获限mapper接口实例
UserMapper userMapper = session.getMapper(UserMapper.class);
//查询订单信息
List<OrdersCustom> list = userMapper.findOrdersList();
System.out.println(list);
//关闭session
session.close();
}
定义专门的po类作为输出类型,其中定义了sql查询结果集所有的字段。此方法较为简单,企业中使用普遍。
实现方案二:
使用resultMap,定义专门的resultMap用于映射一对一查询结果。
Sql语句:
SELECT
orders.*,
user.username,
user.address
FROM
orders,
user
WHERE orders.user_id = user.id
定义po类:
在Orders类中加入User属性,user属性中用于存储关联查询的用户信息,因为订单关联查询用户是一对一关系,所以这里使用单个User对象存储关联查询的用户信息。
Mapper.xml:
<!-- 查询订单关联用户信息使用resultmap -->
<resultMap type="Orders"id="orderUserResultMap">
<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"/>
<!-- 一对一关联映射 -->
<!--
property:Orders对象的user属性
javaType:user属性对应 的类型
-->
<association property="user"javaType="po.User">
<!-- column:user表的主键对应的列 property:user对象中id属性-->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findOrdersWithUserResultMap" resultMap="orderUserResultMap">
SELECT
o.id,
o.user_id,
o.number,
o.createtime,
o.note,
u.username,
u.address
FROM
orders o
JOIN `user` u ON u.id = o.user_id
</select>
这里resultMap指定orderUserResultMap。
association:表示进行关联查询单条记录
property:表示关联查询的结果存储在.mybatis.po.Orders的user属性中
javaType:表示关联查询的结果类型
<id property="id" column="user_id"/>:查询结果的user_id列对应关联对象的id属性,这里是<id />表示user_id是关联查询对象的唯一标识。
<result property="username" column="username"/>:查询结果的username列对应关联对象的username属性。
Mapper接口:
public List<Orders> findOrdersListResultMap() throws Exception;
测试代码:
public void testfindOrdersListResultMap()throws Exception{
//获取session
SqlSession session = sqlSessionFactory.openSession();
//获限mapper接口实例
UserMapper userMapper = session.getMapper(UserMapper.class);
//查询订单信息
List<Orders> list = userMapper.findOrdersList2();
System.out.println(list);
//关闭session
session.close();
}
使用association完成关联查询,将关联查询信息映射到pojo对象中。
Ⅱ、一对多查询
案例:查询所有用户信息及用户关联的订单信息。
用户信息和订单信息为一对多关系。
使用resultMap实现如下:
Sql语句:
SELECT
u.*, o.id oid,
o.number,
o.createtime,
o.note
FROM
`user` u
LEFT JOIN orders o ON u.id = o.user_id
定义po类:
在User类中加入List<Orders> orders属性
Mapper.xml
<resultMap type="user" id="userOrderResultMap">
<!-- 用户信息映射 -->
<id property="id"column="id"/>
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
<!-- 一对多关联映射 -->
<collection property="orders" ofType="orders">
<id property="id"column="oid"/>
<!--用户id已经在user对象中存在,此处可以不设置-->
<!-- <result property="userId" column="id"/> -->
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<result property="note" column="note"/>
</collection>
</resultMap>
<select id="getUserOrderList" resultMap="userOrderResultMap">
SELECT
u.*, o.id oid,
o.number,
o.createtime,
o.note
FROM
`user` u
LEFT JOIN orders o ON u.id = o.user_id
</select>
collection部分定义了用户关联的订单信息。表示关联查询结果集。
property="orders":关联查询的结果集存储在User对象的上哪个属性。
ofType="orders":指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也可以使用全限定名。
<id />及<result/>的意义同一对一查询。
Mapper接口:
List<User> getUserOrderList();
测试代码:
@Test
public void getUserOrderList() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User>result = userMapper.getUserOrderList();
for (User user : result) {
System.out.println(user);
}
session.close();
}