上犹电脑信息网我们一直在努力
您的位置:上犹电脑信息网 > 文件问题 > Mybatis学习——Mapper.xml映射文件-xml文件

Mybatis学习——Mapper.xml映射文件-xml文件

作者:上犹日期:

返回目录:文件问题

  • 简介
Mybatis学习——Mapper.xml映射文件

Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心。

映射文件中有很多属性,常用的就是parameterType(输入类型)、resultType(输出类型)、resultMap()、rparameterMap()。

  • parameterType(输入类型)

1、#{}与${}

#{}实现的是向prepareStatement中的预处理语句中设置参数值,sql语句中#{}表示一个占位符即?。

<!-- 根据id查询用户信息 -->
<select id="findUserById" parameterType="int" resultType="user"> select * from user where id = #{id}
</select>

使用占位符#{}可以有效防止sql注入,在使用时不需要关心参数值的类型,mybatis会自动进行java类型和jdbc类型的转换。#{}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

${}和#{}不同,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。使用${}不能防止sql注入,但是有时用${}会非常方便,如下的例子:

<!-- 根据名称模糊查询用户信息 -->
<select id="selectUserByName" parameterType="string" resultType="user">
select * from user where username like '%${value}%'
</select>

如果本例子使用#{}则传入的字符串中必须有%号,而%是人为拼接在参数中,显然有点麻烦,如果采用${}在sql中拼接为%的方式则在调用mapper接口传递参数就方便很多。

//如果使用占位符号则必须人为在传参数中加%

List<User> list = userMapper.selectUserByName("%张三%");

//如果使用${}原始符号则不用人为在参数中加%

List<User>list = userMapper.selectUserByName("张三");

再比如order by排序,如果将列名通过参数传入sql,根据传的列名进行排序,应该写为:

ORDER BY ${columnName},如果使用#{}将无法实现此功能。

2、传递简单类型

传递简单类型只需要注意#{}与${}的使用就可以。

3、传递pojo对象

Mybatis使用ognl表达式解析对象字段的值,如下例子:

<!—传递pojo对象综合查询用户信息 -->
<select id="findUserByUser" parameterType="user" resultType="user">
select * from user where id=#{id} and username like '%${username}%'
</select>

测试代码:

 Public void testFindUserByUser()throws Exception{
//获取session
SqlSession session = sqlSessionFactory.openSession();
//获限mapper接口实例
UserMapper userMapper = session.getMapper(UserMapper.class);
//构造查询条件user对象
User user = new User();
user.setId(1);
user.setUsername("管理员");
//传递user对象查询用户列表
List<User>list = userMapper.findUserByUser(user);
//关闭session
session.close();
}

如果将username写错后,会报以下异常

org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'dusername' in 'class com.luchao.mybatis.first.po.User' ### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'dusername' in 'class com.luchao.mybatis.first.po.User'

可以看出MyBatis是通过反射来讲java对象映射到查询参数中的。

4、传递pojo包装对象

开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。

(1)、定义包装对象

定义包装对象将查询条件(pojo)以类组合的方式包装起来。

public class QueryVo {
private User user;
//自定义用户扩展类
private UserCustom custom;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserCustom getCustom() {
return custom;
}
public void setCustom(UserCustom custom) {
this.custom = custom;
}
}

(2)、 mapper.xml映射文件

<select id="findUser" parameterType="com.luchao.mybatis.first.po.QueryVo" resultType="com.luchao.mybatis.first.po.User">
select * from user where username like '%${user.username}%' and sex = #{user.sex}
</select>

说明:mybatis底层通过ognl从pojo中获取属性值:#{user.username},user即是传入的包装对象的属性。

5、传递hashmap

Sql映射文件定义如下:

<select id="findUserByIdMap" parameterType="hashmap" resultType="com.luchao.mybatis.first.po.User">
select * from user where id = #{id}
</select>

测试代码:

Public void testFindUserByHashmap()throws Exception{
//获取session
SqlSession session = sqlSessionFactory.openSession();
//获限mapper接口实例
UserMapper userMapper = session.getMapper(UserMapper.class);
//构造查询条件Hashmap对象
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("id", 1);
//传递Hashmap对象查询用户列表
List<User>list = userMapper.findUserByHashmap(map);
//关闭session
session.close();
}

传递的map中的key和sql中解析的key不一致。测试结果没有报错,只是通过key获取值为空。这种用法一般用在POJO与数据库字段不一致的时候。

  • parameterMap和resultMap

resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。

下面是在数据库列于POJO不一致的时候,将输入参数映射到数据库列的一种方式 

<resultMap type="Book.dao.Book" id="BookResultMap">
<id column="id" property="id"/>
<result column="name" property="bookName"/>
<result column="price" property="bookPrice"/>
</resultMap>

<!-- resultMap:resultMap的id ,bookName:resultMap的property,即实体类中的属性 -->
<parameterMap type="Book.dao.Book" id="BookParameterMap">
<parameter property="bookName" resultMap="BookResultMap" />
<parameter property="bookPrice" resultMap="BookResultMap" />
</parameterMap>
<!-- 保存一个Book -->
<insert id="saveBook" parameterMap="BookParameterMap">
insert into BOOK_MANAGE
(ID,NAME,PRICE)
values
(Bookmanage_Seq.Nextval,#{bookName},#{bookPrice})
</insert>
<!-- 根据ID修改Book -->
<update id="updatePersnById" parameterMap="BookParameterMap">
update BOOK_MANAGE
set
NAME=#{bookName},
PRICE=#{bookPrice}
WHERE id=#{id}
</update>

当查询的结果与POJO名字不一致的时候,用resultMap来实现映射。

<resultMap type="user" id="userMap">
<id column="id_" property="id" />
<result column="username_" property="username" />
</resultMap>
<select id="findUserMapById" parameterType="java.lang.Integer" resultMap="userMap" >
select id id_,username username_ from user where id = #{id}
</select>

<id />:此属性表示查询结果集的唯一标识,非常重要。如果是多个字段为复合唯一约束则定义多个<id />。

Property:表示person类的属性。

Column:表示sql查询出来的字段名。

Column和property放在一块儿表示将sql查询出来的字段映射到指定的pojo类属性上。

<result />:普通结果,即pojo的属性。

使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。

  • resultType(输出类型)

1、输出简单类型

映射文件:

<select id="findUserCount" parameterType="user" resultType="int">
select count(1) from user
</select>

输出简单类型必须查询出来的结果集有一条记录,最终将第一个字段的值转换为输出类型。使用session的selectOne可查询单条记录。

2、输出pojo对象

映射文件

 <!-- 根据id查询用户信息 -->
<select id="findUserById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>

3、输出pojo列表

映射文件:

<!-- 根据名称模糊查询用户信息 -->
<select id="findUserByUsername" parameterType="string" resultType="user">
select * from user where username like '%${value}%'
</select>

注意:MyBatis会根据Mapper接口方法的返回类型来选择调用selectOne还是selectList方法,如果是List这调用selectList方法,如果是POJO则调用selectOne方法。

4、输出hashmap

输出pojo对象可以改用hashmap输出类型,将输出的字段名称作为map的key,value为字段值。

resultType总结:

输出pojo对象和输出pojo列表在sql中定义的resultType是一样的。返回单个pojo对象要保证sql查询出来的结果集为单条,内部使用session.selectOne方法调用,mapper接口使用pojo对象作为方法返回值。返回pojo列表表示查询出来的结果集可能为多条,内部使用session.selectList方法,mapper接口使用List<pojo>对象作为方法返回值。

  • 动态SQl

mybatis核心 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。对查询条件进行判断,如果输入参数不为空才进行查询条件拼接。

1、if

<!-- 传递pojo综合查询用户信息 -->
<select id="findUserList" parameterType="user" resultType="user">
select * from user
where 1=1
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</select>

2、Where

上面的配置也可以按如下来写:

<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 />可以自动处理第一个and。

3、foreach

向sql传递数组或List,mybatis使用foreach解析,如下:

如果我们需要传入多个ID来查询多个用户的信息,这也就可以使用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)

index:为数组的下标。

item:为数组每个元素的名称,名称随意定义

open:循环开始

close:循环结束

separator:中间分隔输出

通过POJO传入List,映射文件如下:

<if test="ids!=null and ids.size>0">

<foreach collection="ids" open=" and id in(" close=")" item="id" separator="," >

#{id}

</foreach>

</if>

或者:

<if test="ids!=null and ids.size>0">
<foreach collection="ids" open=" and (" close=")" item="id" separator="," >
id = #{id}
</foreach>
</if>

传递单个List

传递List类型在编写mapper.xml没有区别,唯一不同的是只有一个List参数时它的参数名为list。

配置文件如下:

<select id="selectUserByList" parameterType="java.util.List" resultType="user">
select * from user
<where>
<!-- 传递List,List中是pojo -->
<if test="list!=null">
<foreach collection="list" item="item" open="and id in("separator=","close=")">
#{item.id}
</foreach>
</if>
</where>
</select>

传递单个数组(数组中是POJO)

<!-- 传递数组综合查询用户信息 -->
<select id="selectUserByArray" parameterType="Object[]" resultType="user">
select * from user
<where>
<!-- 传递数组 -->
<if test="array!=null">
<foreach collection="array" index="index" item="item" open="and id in("separator=","close=")">
#{item.id}
</foreach>
</if>
</where>
</select>

sql只接收一个数组参数,这时sql解析参数的名称mybatis固定为array,如果数组是通过一个pojo传递到sql则参数的名称为pojo中的属性名。

传递单个数组(数组中是简单类型)

配置文件如下:

<!-- 传递数组综合查询用户信息 -->
<select id="selectUserByArray" parameterType="Object[]" resultType="user">
select * from user
<where>
<!-- 传递数组 -->
<if test="array!=null">
<foreach collection="array"index="index"item="item"open="and id in("separator=","close=")">
#{item}
</foreach>
</if>
</where>
</select>

如果数组中是简单类型则写为#{item},不用再通过ognl获取对象属性值了。

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>

如果有多个statement都使用相同的查询条件,那么就可以把查询条件抽取出来作为单独的Sql片段。

Sql片段配置:

<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片段”/>

Mapper配置文件中常用的基本属性就是这些,如果还有其他的特殊需求可以根据需要来进行修改配置。另外,在我们的设计中,如果已经定义好了基本的POJO在引用的时候可以在定义一个视图查询层的POJO在其中封装基本的POJO和自定义的POJO(继承基本的POJO),这样就可以较容易实现扩展。当数据库需求有变化的时候可以不修改基本POJO,而修改自定义的POJO,这样就可以实现较好的扩展,而不影响其他模块。如果前端需求有变动,可以通过修改前端的POJO来实现较小的改动。如下实现:

基本的POJO类型:

public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.id+"-"+this.username+"-"+this.sex+"-"+this.address+"-"+this.birthday.toString();
}

}

自定义的POJO继承基本的POJO:

public class UserCustom extends User{
}

如果我们的数据库有变动,我们可以在UserCustom添加属性,只满足当前修改。

前端POJO实现:

public class QueryVo {
private User user;
//自定义用户扩展类
private UserCustom custom;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserCustom getCustom() {
return custom;
}
public void setCustom(UserCustom custom) {
this.custom = custom;
}
}

可以满足基本的需求,如果我们在查询中需要加入其他查询条件,如:商品、订单等,只需要修改QueryVo,这样就可以实现较好的可扩展性。

相关阅读

关键词不能为空
极力推荐

电脑蓝屏_电脑怎么了_win7问题_win10问题_设置问题_文件问题_上犹电脑信息网

关于我们