使用#{}占位符,或者${}进行sql拼接。
Mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称。
开发中通过可以使用pojo传递查询条件。
查询条件可能是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如查询用户信息的时候,将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
包装对象:Pojo类中的一个属性是另外一个pojo。
需求:根据用户名模糊查询用户信息,查询条件放到QueryVo的user属性中。
package cn.zdfy.mapper;
import cn.zdfy.User;
public class QueryVo {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
SELECT * FROM user WHERE username LIKE ‘%张%’
在UserMapper.xml中配置sql,如下:
<mapper namespace="cn.zdfy.mapper.UserMapper">
<select id="queryUserByQueryVo" parameterType="queryVo"
resultType="user">
select * from user where username like '%${user.username}%'
select>
mapper>
/**
* 根据包类查询用户
*
* @param qv
* @return
*/
List queryUserByQueryVo(QueryVo qv);
@Test
public void fun3() {
// 获取sqlSession,和spring整合后由spring管理
SqlSession sqlSession = sqlSessionFactory.openSession();
// 从sqlSession中获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
QueryVo qv = new QueryVo();
User u = new User();
u.setUsername("张");
qv.setUser(u);
List list = userMapper.queryUserByQueryVo(qv);
for(User user:list) {
System.out.println(user);
}
sqlSession.close();
}
需求:查询用户表数据条数
sql:SELECT count(*) FROM user
<select id="queryUserCount" resultType="int">
select count(*) from user
select>
在UserMapper添加方法,如下
/**
* 查询用户数据条数
*
* @return
*/
int queryUserCount();
@Test
public void fun4() {
SqlSession openSession = sqlSessionFactory.openSession();
UserMapper mapper = openSession.getMapper(UserMapper.class);
int queryUserCount = mapper.queryUserCount();
System.out.println(queryUserCount);
openSession.close();
}
resultType可以指定将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。
如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。
resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
需求:查询订单表order的所有数据
sql:SELECT id, user_id, number, createtime, note FROM order
package cn.zdfy;
import java.util.Date;
public class Order {
private int id;
private Integer userId;
private String number;
private Date createtime;
private String note;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
创建OrderMapper.xml配置文件,如下:
<mapper namespace="cn.zdfy.mapper.OrderMapper">
<select id="queryOrderAll" resultType="order">
select id, user_id, number, createtime, note from orders
select>
mapper>
package cn.zdfy.mapper;
import java.util.List;
import cn.zdfy.Order;
public interface OrderMapper {
/**
* 查询所有订单
*
* @return
*/
List queryOrderAll();
}
package cn.zdfy;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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.Before;
import org.junit.Test;
import cn.zdfy.mapper.OrderMapper;
public class OrderMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}
@Test
public void testQueryAll() {
SqlSession sqlSession = this.sqlSessionFactory.openSession();
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List queryOrderAll = mapper.queryOrderAll();
for (Order o : queryOrderAll) {
System.out.println("o===============" + o);
}
sqlSession.close();
}
}
DEBUG [main] - <== Total: 3
o===============Order [id=3, userId=null, number=1000010, createtime=Wed Feb 04 13:22:35 CST 2015, note=null]
o===============Order [id=4, userId=null, number=1000011, createtime=Tue Feb 03 13:22:41 CST 2015, note=null]
o===============Order [id=5, userId=null, number=1000012, createtime=Thu Feb 12 16:13:23 CST 2015, note=null]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@7a765367]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@7a765367]
DEBUG [main] - Returned connection 2054574951 to pool.
发现userId为null
解决方案:使用resultMap
由于上边的mapper.xml中sql查询列(user_id)和Order类属性(userId)不一致,所以查询结果不能映射到pojo中。
需要定义resultMap,把orderResultMap将sql查询列(user_id)和Order类属性(userId)对应起来
改造OrderMapper.xml,如下:
<mapper namespace="cn.zdfy.mapper.OrderMapper">
<resultMap type="order" id="orderResultMap">
<id property="id" column="id" />
<result property="userId" column="user_id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />
resultMap>
<select id="queryOrderAll" resultMap="orderResultMap">
select id, user_id,
number, createtime, note from orders
select>
mapper>
只需要修改Mapper.xml就可以了,再次测试结果如下
DEBUG [main] - <== Total: 3
o===============Order [id=3, userId=1, number=1000010, createtime=Wed Feb 04 13:22:35 CST 2015, note=null]
o===============Order [id=4, userId=1, number=1000011, createtime=Tue Feb 03 13:22:41 CST 2015, note=null]
o===============Order [id=5, userId=10, number=1000012, createtime=Thu Feb 12 16:13:23 CS
通过mybatis提供的各种标签方法实现动态拼接sql。
需求:根据性别和名字查询用户
查询sql:
SELECT id, username, birthday, sex, address FROMuser
WHERE sex = 1 AND username LIKE ‘%张%’
UserMapper.xml配置sql,如下:
<select id="queryUserByWhere" parameterType="user" resultType="user">
select id, username, birthday, sex, address from user where
sex = #{sex} and username like '%${username}%'
select>
编写Mapper接口,如下:
/**
* 根据条件查询用户
*
* @param user
* @return
*/
List queryUserByWhere(User user);
@Test
public void testQueryByWhere() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User u = new User();
u.setSex("1");
u.setUsername("张");
List list = mapper.queryUserByWhere(u);
for (User user : list) {
System.out.println("===== " + user);
}
sqlSession.close();
}
DEBUG [main] - <== Total: 3
===== User [id=10, username=张三, sex=1, birthday=Thu Jul 10 00:00:00 CST 2014, address=北京市]
===== User [id=16, username=张小明, sex=1, birthday=null, address=河南郑州]
===== User [id=24, username=张三丰, sex=1, birthday=null, address=河南郑州]
注释掉 u.setSex(“1”),测试结果如下
DEBUG [main] - ==> Preparing: select id, username, birthday, sex, address from user where sex = ? and username like '%张%'
DEBUG [main] - ==> Parameters: null
DEBUG [main] - <== Total: 0
测试结果二很显然不合理。
按照之前所学的,要解决这个问题,需要编写多个sql,查询条件越多,需要编写的sql就更多了,显然这样是不靠谱的。
解决方案,使用动态sql的if标签
改造UserMapper.xml,如下:
<select id="queryUserByWhere" parameterType="user" resultType="user">
select id, username, birthday, sex, address from user where
1=1
<if test=" sex!=null and sex !='' ">if>
<if test="username != null and username != ''">
and username like
'%${username}%'
if>
select>
注意字符串类型的数据需要要做不等于空字符串校验。
DEBUG [main] - <== Total: 3
===== User [id=10, username=张三, sex=1, birthday=Thu Jul 10 00:00:00 CST 2014, address=北京市]
===== User [id=16, username=张小明, sex=1, birthday=null, address=河南郑州]
===== User [id=24, username=张三丰, sex=1, birthday=null, address=河南郑州]
上面的sql还有where 1=1 这样的语句,很麻烦
可以使用where标签进行改造
改造UserMapper.xml,如下
<select id="queryUserByWhere" parameterType="user" resultType="user">
select id, username, birthday, sex, address from user
<where>
<if test=" sex!=null and sex !='' ">if>
<if test="username != null and username != ''">
and username like
'%${username}%'
if>
where>
select>
测试效果如下
DEBUG [main] - <== Total: 3
===== User [id=10, username=张三, sex=1, birthday=Thu Jul 10 00:00:00 CST 2014, address=北京市]
===== User [id=16, username=张小明, sex=1, birthday=null, address=河南郑州]
===== User [id=24, username=张三丰, sex=1, birthday=null, address=河南郑州]
Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的。
把上面例子中的id, username, birthday, sex, address提取出来,作为sql片段,如下
<select id="queryUserByWhere" parameterType="user" resultType="user">
select
<include refid="userFields" />
from user
<where>
<if test=" sex!=null and sex !='' ">if>
<if test="username != null and username != ''">
and username like
'%${username}%'
if>
where>
select>
<sql id="userFields">
id, username, birthday, sex, address
sql>
如果要使用别的Mapper.xml配置的sql片段,可以在refid前面加上对应的Mapper.xml的namespace
向sql传递数组或List,mybatis使用foreach解析,如下:
根据多个id查询用户信息
查询sql:
SELECT * FROM user WHERE id IN (1,10,24)
如下 在pojo中定义list属性ids存储多个用户id,并添加getter/setter方法
package cn.zdfy.mapper;
import java.util.List;
import cn.zdfy.User;
public class QueryVo {
private User user;
private List ids;
public List getIds() {
return ids;
}
public void setIds(List ids) {
this.ids = ids;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
UserMapper.xml添加sql,如下:
<select id="queryUserByIds" parameterType="queryVo" resultType="user">
select * from user
<where>
<foreach collection="ids" item="item" open="id in (" close=")"
separator=",">
#{item}
foreach>
where>
select>
测试方法如下:
@Test
public void testQueryUserByIds() {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
QueryVo qv = new QueryVo();
List ids = new ArrayList<>();
ids.add(1);
ids.add(10);
ids.add(16);
qv.setIds(ids);
List list = mapper.queryUserByIds(qv);
for (User u : list) {
System.out.println("uuuu==========" + u);
}
// mybatis和spring整合,整合之后,交给spring管理
sqlSession.close();
}
测试结果
DEBUG [main] - <== Total: 3
uuuu==========User [id=1, username=王五, sex=2, birthday=null, address=null]
uuuu==========User [id=10, username=张三, sex=1, birthday=Thu Jul 10 00:00:00 CST 2014, address=北京市]
uuuu==========User [id=16, username=张小明, sex=1, birthday=null, address=河南郑州]
需求:查询所有订单信息,关联查询下单用户信息。
注意:因为一个订单信息只会是一个人下的订单,所以从查询订单信息出发关联查询用户信息为一对一查询。如果从用户信息出发查询用户下的订单信息则为一对多查询,因为一个用户可以下多个订单。
sql语句:
SELECT
o.id,
o.user_id userId,
o.number,
o.createtime,
o.note,
u.username,
u.address
FROM
`order` o
LEFT JOIN `user` u ON o.user_id = u.id
使用resultType,改造订单pojo类,此pojo类中包括了订单信息和用户信息
这样返回对象的时候,mybatis自动把用户信息也注入进来了
OrderUser类继承Order类后OrderUser类包括了Order类的所有字段,只需要定义用户的信息字段即可,如下:
package cn.zdfy;
public class OrderUser extends Order {
private String username;
private String address;
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;
}
@Override
public String toString() {
return "OrderUser [username=" + username + ", address=" + address + "]";
}
}
在UserMapper.xml添加sql,如下
在UserMapper接口添加方法,如下:
/**
* 一对一关联,查询订单同时包含用户信息
*
* @return
*/
List queryOrderUser();
@Test
public void testQueryOrderUser() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List list = mapper.queryOrderUser();
for (OrderUser ou : list) {
System.out.println(ou);
}
sqlSession.close();
}
DEBUG [main] - <== Total: 3
Order [id=3, userId=null, number=1000010, createtime=Wed Feb 04 13:22:35 CST 2015, note=null]
Order [id=4, userId=null, number=1000011, createtime=Tue Feb 03 13:22:41 CST 2015, note=null]
Order [id=5, userId=null, number=1000012, createtime=Thu Feb 12 16:13:23 CST 2015, note=null]
定义专门的pojo类作为输出类型,其中定义了sql查询结果集所有的字段。此方法较为简单,企业中使用普遍。
使用resultMap,定义专门的resultMap用于映射一对一查询结果。
在Order类中加入User属性,user属性中用于存储关联查询的用户信息,因为订单关联查询用户是一对一关系,所以这里使用单个User对象存储关联查询的用户信息。
改造Order如下
package cn.zdfy;
import java.util.Date;
public class Order {
private int id;
private Integer userId;
private String number;
private Date createtime;
private String note;
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "Order [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
+ ", note=" + note + ", user=" + user + "]";
}
}
这里resultMap指定orderUserResultMap,如下:
<resultMap type="order" id="orderUserResultMap">
<id property="id" column="id">id>
<result property="userId" column="user_id">result>
<result property="number" column="number">result>
<result property="createtime" column="createtime">result>
<result property="note" column="note">result>
<association property="user" javaType="user">
<id property="id" column="user_id" />
<result property="username" column="username" />
<result property="address" column="address" />
association>
resultMap>
<select id="queryOrderUserResultMap" resultMap="orderUserResultMap">
select
o.id,
o.user_id,
o.number,
o.createtime,
o.note,
u.username,
u.address
from orders
o
left join
user u on o.user_id = u.id
select>
/**
* 一对一关联,查询订单,订单内部包含user属性
*
* @return
*/
List queryOrderUserResultMap();
@Test
public void testQueryOrderUserResultMap() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List list = mapper.queryOrderUserResultMap();
for (Order o : list) {
System.out.println(o);
}
sqlSession.close();
}
DEBUG [main] - <== Total: 3
Order [id=3, userId=1, number=1000010, createtime=Wed Feb 04 13:22:35 CST 2015, note=null, user=User [id=1, username=王五, sex=null, birthday=null, address=null]]
Order [id=4, userId=1, number=1000011, createtime=Tue Feb 03 13:22:41 CST 2015, note=null, user=User [id=1, username=王五, sex=null, birthday=null, address=null]]
Order [id=5, userId=10, number=1000012, createtime=Thu Feb 12 16:13:23 CST 2015, note=null, user=User [id=10, username=张三, sex=null, birthday=null, address=北京市]]
案例:查询所有用户信息及用户关联的订单信息。
用户信息和订单信息为一对多关系。
sql语句:
SELECT
u.id,
u.username,
u.birthday,
u.sex,
u.address,
o.id oid,
o.number,
o.createtime,
o.note
FROM
`user` u
LEFT JOIN `order` o ON u.id = o.user_id
在User类中加入List orders属性,如下
private List<Order> orders;
在UserMapper.xml添加sql,如下:
<resultMap type="user" id="userOrderResultMap">
<id property="id" column="id">id>
<result property="username" column="username" />
<result property="birthday" column="birthday" />
<result property="sex" column="sex" />
<result property="address" column="address" />
<collection property="orders" javaType="list" ofType="order">
<id property="id" column="oid" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />
collection>
resultMap>
<select id="queryUserOrder" resultMap="userOrderResultMap">
select
u.id,
u.username,
u.birthday,
u.sex,
u.address,
o.number,
o.createtime,
o.note
from
user u
left join orders o on u.id=o.user_id
select>
编写UserMapper接口,如下:
/**
* 一对多关联,查询用户,用户内部包含该用户的所有订单
*
* @return
*/
List queryUserOrder();
@Test
public void testQueryUserOrder() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List list = mapper.queryUserOrder();
for (User u : list) {
System.out.println(u);
}
sqlSession.close();
}
DEBUG [main] - <== Total: 8
User [id=1, username=王五, sex=2, birthday=null, address=null, orders=[Order [id=0, userId=null, number=1000010, createtime=Wed Feb 04 13:22:35 CST 2015, note=null, user=null], Order [id=0, userId=null, number=1000011, createtime=Tue Feb 03 13:22:41 CST 2015, note=null, user=null]]]
User [id=10, username=张三, sex=1, birthday=Thu Jul 10 00:00:00 CST 2014, address=北京市, orders=[Order [id=0, userId=null, number=1000012, createtime=Thu Feb 12 16:13:23 CST 2015, note=null, user=null]]]
User [id=16, username=张小明, sex=1, birthday=null, address=河南郑州, orders=[]]
User [id=22, username=陈小明, sex=1, birthday=null, address=河南郑州, orders=[]]
User [id=24, username=张三丰, sex=1, birthday=null, address=河南郑州, orders=[]]
User [id=25, username=陈小明, sex=1, birthday=null, address=河南郑州, orders=[]]
User [id=26, username=王五, sex=null, birthday=null, address=null, orders=[]]
1、SqlSessionFactory对象应该放到spring容器中作为单例存在。
2、传统dao的开发方式中,应该从spring容器中获得sqlsession对象。
3、Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。
4、数据库的连接以及数据库连接池事务管理都交给spring容器来完成。
1、spring的jar包
2、Mybatis的jar包
3、Spring+mybatis的整合包。
4、Mysql的数据库驱动jar包。
5、数据库连接池的jar包。
jar包位置如下所示: