Mapper.xml映射文件

查询订单关联查询用户:

使用resultType,ordersCustom可以通过继承orders获得其属性,再添加我们需要的用户字段.

使用resultMap,orders表中通过封装user对象来关联用户.

Mapper.xml映射文件

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

2.1 parameterType(输入类型)

2.1 .1#{}与${}    #{}:表示占位符?,它可以防止sql注入,它会把SQL语句和参数发到数据库,匹配数据库表的字段是否一致.括号内最好填写实体类属性.

2.1.2  ${value}:表示拼接字符,实现sql拼接,所以无法防止sql注入.例如模糊查询时:'%${value}%',parameterType="user"括号里可写其字段名称如'%${username}%'  

又例如将列名通过sql传入,对列名进行排序.order by ${columnName}.-

2.1.3 传递pojo类,使用ognl表达式解析字段的值

<!—传递pojo对象综合查询用户信息 -->

<select id="findUserByUser" parameterType="user" resultType="user">

   select * from user where id=#{id} and username like '%${username}%'

</select>

2.1.4 传递pojo包装对象:定义包装对象查询条件(pojo)以类组合的方式包装起来

public class QueryVo(){  private User user;          //自定义用户扩展类   private UserCustomer usercustom;}

mapper.xml映射文件:

<select id="findUserList" parameterType="queryVo" resultType="user">

select*from user where username=#{user.username} and sex =#{user.sex}       </select>

说明:mybatis底层通过ognl从pojo获取属性值#{user.username} ,user为包装类对象的属性,queryVo是别名,即包装类对象类型.

2.1.5 传递hashmap      括号里为hashmap的key

<select id="findUserByHasmap" parameterType="hashmap" resultType="user">
select*from user   where id=#{id} and username like '%${username}%    </select>

2.2 resultType(输出类型)   

简单类型:int/string/float   自定义的pojo:表示单条记录所映射的pojo类型,映射要求:sql查询的列名和pojo的属性名一致

2.2.1 输出简单类型

mapper.xml

<select id="findUserCount" parameterType="queryUserVo" resulttype="int">  select count(*) from user
where username like '%${user.username}%'and sex=#{user.sex} </select>

mapper.java-----输出pojo对象和列表sql定义的resultType是一样的.session.selectOne方法和session.selectList方法

public int findUsercount (QueryUserVo queryUserVo) throws Exception;

 2.2 resultMap(还可实现延迟加载功能)

resultMap当列名和属性名不一致时,可以通过resultMap定义列名和属性名的映射关系,完成映射.还可实现(一对一/一对多)

UserMapper.xml
<select id="findUserByResultMap" parameterType="int" resultType="queryUserResultMap"> select id id_,username username_,birthday birthday_,sex sex_,address address _ from User where id=#{id} </select>
<!-- 使用resultMap将列名和pojo的属性值作一个对应关系,完成映射
id:唯一标识 一个元素
type:最终映射的pojo类型
-->
<resultMap type="user" id="queryUserResultMap">
    <!-- id标识 查询结果集中唯一标识列
    column:结果集中唯 一标识 的列名
    property:将唯一标识 的列所映射到的type指定的pojo的属性名
     -->
    <id column="id_" property="id"/>
    <!-- 如果结果集有多个列组合成一个唯 一标识,定义两个id标签 -->
    <!-- result表示:普通列 -->
    <result column="username_" property="username"/>
    <result column="birthday_" property="birthday"/>
    <result column="sex_" property="sex"/>
    <result column="address_" property="address"/>

<association property="user" javaType="cn.itcast.mybatis.po.User">
<!-- id:用户信息的唯一标识
result:用户信息列
property:将关联查询的列映射到user的哪个属性中
-->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="address" property="address"/>

</association>

</resultMap>

userMapper.java
public User findUserByResultMap(int id) throws Exception;

原文地址:https://www.cnblogs.com/wwwzzz/p/8276160.html