MyBatis

一、基础知识

mybatis 规定 mapper.xml 中每一个 SQL 语句形式上只能有一个 @parameterType 和一个 @resultType

1)返回值是一个对象的集合,@resultType 中只能写该对象的类型,而不是写 List<T>

2)输入参数可以用 #{} 和 ${} 两种取值方法,两者区别与联系:

① 当传入类型为 JDBC 基本类型(8种java基本类型+String)时,#{} 里面可以写成任意值,${} 里面必须写 value  
② 当传入类型为对象时,两种方式里面都应该写成类中属性名
③ #{} 方式传值会将传入的值当做一个字符串处理,会自动将其加入"",而 ${} 方式则不会  
④ #{} 方式能够有效防止 SQL 注入,而 ${} 不会,因此能够用 #{} 就不要用 ${}
⑤ ${} 的适用场景是利用数据库中的字段动态排序等例如想要根据id排序  
  如果用 #{} 传入 id,SQL 语句会变成 order by "id" 这样的 SQL 语句不能排序,  
  因此只能用 ${} ,对应的 SQL 语句是 order by id 符合要求

二、输入映射 - parameterType、parameterMap(已废弃)

1)基本类型 - 当输入参数为JDBC基本类型,则可以直接用#{xxx}或者${value}取值

<select id="selectUserById" parameterType="int" resultType="com.sikiedu.beans.User">
    SELECT * FROM user WHERE id = #{id}
</select>

2)自定义对象 - 当输入参数为对象时,MyBatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo的属性名称

<insert id="insertUser" parameterType="com.sikiedu.beans.User">
    INSERT INTO user VALUES(null,#{username},#{userpassword},#{balance},#{grgisterdate})
</insert>

<update id="updateUser" parameterType="com.sikiedu.beans.User">
    UPDATE user SET username = #{username} WHERE id = #{id}
</update>

3)自定义包装类 - 开发中通过pojo传递查询条件,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件,这时可以使用包装对象传递输入参数。即一个pojo类的属性是另一个pojo类对象。

Vo包装类:

 1 package com.sikiedu.beans;
 2 
 3 import java.util.List;
 4 
 5 public class UserVo extends User {
 6     // 维护一个Role集合
 7     private List<Role> roleList;
 8 
 9     public List<Role> getRole() {
10         return roleList;
11     }
12 
13     public void setRole(List<Role> roleList) {
14         this.roleList = roleList;
15     }
16 
17     @Override
18     public String toString() {
19         return "UserVo [ID=" + getId() + "	 username=" + getUsername() + "	 Grgisterdate=" + getGrgisterdate()
20                 + "	 role=" + roleList + "]";
21     }
22 
23 }
UserVo.java

UserMapper接口中定义方法:

// 通过包装类UserVo查询用户
public User selectUserByUserVoId(UserVo vo);

UserMapper.xml - sql语句

<select id="selectUserByUserVoId" parameterType="com.sikiedu.beans.UserVo" resultType="user">
    SELECT * FROM user WHERE id = #{id}
</select>

4)键值对 / HashMap - 则#{key}即可取得该key对应的value

<select id="queryStudentBystuageOrstuNameWithHashMap" parameterType="HashMap" resultType="student" > 
    SELECT stuno,stuname,stuage FROM student
    WHERE stuage= #{stuAge} OR stuname LIKE '%${stuName}%'
<select/>

三、输出映射 - resultType、resultMap

1)resultType

resultType可以把查询结果封装到pojo类型中,但必须pojo类的属性名和查询到的数据库表的字段名一致。 

如果sql查询到的字段与pojo的属性名不一致,则需要使用resultMap将字段名和属性名对应起来,进行手动配置封装,将结果映射到pojo中

基本类型 - 输出基本类型必须查询出来的结果集只有一条记录,最终将第一个字段的值转换为输出类型

<select id="selectUserCount" resultType="int">
    SELECT COUNT(*) FROM user
</select>

自定义对象 - selectOne根据mapper接口的返回值类型选择

<select id="selectUserById" parameterType="Integer" resultType="com.sikiedu.beans.User">
    SELECT * FROM user WHERE id = #{id}
</select>

集合 - selectList根据mapper接口的返回值类型选择

<select id="selectAllUser" resultType="user">
    SELECT  * FROM user
</select> 

2)resultMap

ResultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中。

resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。 

◆ resultMap
  - id:设置ResultMap的id
  - type:指resultMap要映射成的数据类型(返回结果映射的pojo,可以使用别名)。
● id:此属性表示查询结果集的唯一标识,非常重要。如果是多个字段为复合唯一约束则定义多个< id />(复合主键时多个)。 ● result:普通列使用result标签映射。   - property:表示POJO类的属性。   - column:表示sql查询出来的字段名(列名)。
● association:
实体类中将另一个类作为属性association,一对一关系
● collection:实体类中将另一个类的list作为属性,一对多关系
column和property放在一块儿表示将sql查询出来的字段映射到指定的pojo类属性上。

bean对象字段与数据表字段不匹配

例如数据库role表中属性为 idrole int(11),name varchar(45)。
对应的实体类属性为 Integer id,String name,若直接查询select * from role会报错。
这时就可以使用resultMap属性
<!-- 配置resultMap标签,映射不同的字段和属性名 -->
<
resultMap type="Role" id="roleRM"> <id property="id" column="idrole" /> </resultMap> <select id="selectAllRole" resultMap="roleRM"> SELECT * FROM role </select>

自定义包装类

RoleVo包装类:在RoleVo包装类中添加User属性。(一个角色每个用户只能拥有一个)

User是一个引用类型,用于存储关联查询的用户信息,因为关联关系是一对一,所以只需要添加单个属性即可 

 1 package com.sikiedu.beans;
 2 
 3 import java.util.List;
 4 
 5 public class RoleVo extends Role {
 6 
 7     private User user;
 8     private List<Integer> idList;
 9 
10     public User getUser() {
11         return user;
12     }
13 
14     public void setUser(User user) {
15         this.user = user;
16     }
17 
18     public List<Integer> getList() {
19         return idList;
20     }
21 
22     public void setList(List<Integer> idList) {
23         this.idList = idList;
24     }
25 
26     @Override
27     public String toString() {
28         return "RoleVo [ID=" + getId() + "	 name=" + getName() + "	 roletype=" + getRoletype() + "	 user=" + user
29                 + "]";
30     }
31 
32 }
RoleVo.java

配置Mapper.xml配置文件:先使用id和result属性,映射role类的结果集,然后在使用association映射关联对象User的结果集

<resultMap type="RoleVo" id="roleVo">
    <id property="id" column="idrole" />
    <result property="name" column="name" />
    <result property="level" column="level" />
    <result property="roletype" column="roletype" />
    <!-- 一对一关系 -->
    <association property="user" javaType="User">
        <id property="id" column="id" />
        <result property="username" column="username" />
    </association>
</resultMap>
<!-- 一对一关联查询 -->
<select id="selectAllRoleVo" resultMap="roleVo">
    SELECT
    r.idrole,
    r.name,
    r.level,
    r.roletype,
    u.id,
    u.username
    FROM role r
    LEFT JOIN user u
    ON r.idrole = u.id
</select>

关联查询

UserVo包装类:在Vo类添加角色集合属性

 1 package com.sikiedu.beans;
 2 
 3 import java.util.List;
 4 
 5 public class UserVo extends User {
 6     // 维护一个Role集合
 7     private List<Role> roleList;
 8 
 9     public List<Role> getRole() {
10         return roleList;
11     }
12 
13     public void setRole(List<Role> roleList) {
14         this.roleList = roleList;
15     }
16 
17     @Override
18     public String toString() {
19         return "UserVo [ID=" + getId() + "	 username=" + getUsername() + "	 Grgisterdate=" + getGrgisterdate()
20                 + "	 role=" + roleList + "]";
21     }
22 
23 }
UserVo.java

配置Mapper.xml配置文件:先使用id和result配置映射User类的结果,然后使用一对多关系的collection标签配置Role结果

<resultMap type="UserVo" id="userVo">
    <id property="id" column="id" />
    <result property="username" column="username" />
    <result property="grgisterdate" column="grgisterdate" />
    <!-- 一对多关系 -->
    <collection property="roleList" ofType="Role">
        <id property="id" column="idrole" />
        <result property="name" column="name" />
        <result property="roletype" column="roletype" />
    </collection>
</resultMap>
<!-- 一对多关联查询 -->
<select id="selectAllUserVo" resultMap="userVo">
    SELECT
    u.id,
    u.username,
    u.grgisterdate,
    r.idrole,
    r.name,
    r.roletype
    FROM user u
    LEFT JOIN role r
    ON u.id = r.userid
</select>
原文地址:https://www.cnblogs.com/Dm920/p/12049482.html