MyBatis之XML映射器

官方参考:XML映射器

  • MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 致力于减少使用成本,让用户能更专注于 SQL 代码
  • SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):
cache – 该命名空间的缓存配置。
cache-ref – 引用其它命名空间的缓存配置。
resultMap – 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素。
sql – 可被其它语句引用的可重用语句块。
insert – 映射插入语句。
update – 映射更新语句。
delete – 映射删除语句。
select – 映射查询语句。
复制代码

一、select 元素的属性

属性 描述
id 在命名空间中唯一的标识符,可以用来被引用
parameterType 这条语句的参数的类全限定名或别名
resultType 期望从这条语句中返回结果的类全限定名或别名。 注意,如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身的类型。 resultType 和 resultMap 之间只能同时使用一个。
resultMap 对外部 resultMap 的命名引用。
flushCache 将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false
useCache 将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true。
timeout 这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。
fetchSize 这是一个给驱动的建议值,尝试让驱动程序每次批量返回的结果行数等于这个设置值
statementType 可选 STATEMENT,PREPARED 或 CALLABLE。
resultSetType FORWARD_ONLY,SCROLL_SENSITIVE, SCROLL_INSENSITIVE 或 DEFAULT(等价于 unset) 中的一个,
databaseId 如果配置了数据库厂商标识(databaseIdProvider),MyBatis 会加载所有不带 databaseId 或匹配当前 databaseId 的语句;如果带和不带的语句都有,则不带的会被忽略。
resultOrdered 这个设置仅针对嵌套结果 select 语句:如果为 true,将会假设包含了嵌套结果集或是分组,当返回一个主结果行时,就不会产生对前面结果集的引用。 这就使得在获取嵌套结果集的时候不至于内存不够用。默认值:false。
resultSets 这个设置仅适用于多结果集的情况。

二、Insert, Update, Delete 元素的属性

仅适用于insertupdate

属性 描述
useGeneratedKeys MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键 ,默认值:false。
keyProperty 指定能够唯一识别对象的属性,MyBatis 会使用 getGeneratedKeys 的返回值或 insert 语句的 selectKey 子元素设置它的值,默认值:未设置(unset)
keyColumn 设置生成键值在表中的列名,在某些数据库(像 PostgreSQL)中,当主键列不是表中的第一列的时候,是必须设置的。
  • 插入一个user,但不包含Userid
<insert id="insertUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
    insert into user (name, address)
    values (#{name}, #{address});
</insert>
复制代码
  @Test
  public void insertUserTest() {
    try (SqlSession sqlSession = Utils.getSqlSession()) {
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      int res = mapper.insertUser(new User(null, "libai", "印度"));
      if (res > 0)
        System.out.println("插入成功");
      else
        System.out.println("插入失败");
      sqlSession.commit(); // 提交事务,必须!
    }
  }
复制代码

三、插入多个元素(foreach)

int insertUsers(List<User> users);
复制代码
<insert id="insertUsers" parameterType="list">
insert into user (name, address) values
<foreach collection="list" item="item" separator=",">
    (#{item.name}, #{item.address})
</foreach>
</insert>
复制代码

collection=”list”,表示输入参数类型是List的;item=”item”是遍历每个元素的别名;separator=”,”是下面句子的分隔符

  @Test
  public void insertUsersTest() {
    try (SqlSession sqlSession = Utils.getSqlSession()) {
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      List<User> users = new ArrayList<>();
      users.add(new User(null, "李白", "中国"));
      users.add(new User(null, "王维", "中国"));
      users.add(new User(null, "苏轼", "中国"));
      int res = mapper.insertUsers(users);
      if (res > 0)
        System.out.println("插入成功");
      else
        System.out.println("插入失败");
      sqlSession.commit(); // 提交事务,必须!
    }
  }
复制代码

四、重用sql代码片段

  • 这个元素可以用来定义可重用的 SQL 代码片段,以便在其它语句中使用
  • 参数可以静态地(在加载的时候)确定下来,并且可以在不同的 include 元素中定义不同的参数值
<sql id="allParam">
    select *
    from student
</sql>

<select id="getStudentById" resultType="student" parameterType="_int">
    <include refid="allParam"/>
    where id = ${id};
</select>

<select id="getStudentByName" parameterType="string" resultType="student">
    <include refid="allParam"/>
    where name = ${name};
</select>
复制代码
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>
<select id="selectUsers" resultType="map">
  select
    <include refid="userColumns"><property name="alias" value="t1"/></include>,
    <include refid="userColumns"><property name="alias" value="t2"/></include>
  from some_table t1
    cross join some_table t2
</select>
复制代码

五、参数

  • #{}${}的区别
    • #{} 为参数占位符 ?,即sql 预编译;${} 为字符串替换,即 sql 拼接
    • #{} 安全,${} 容易发生SQL注入问题。
  • 将字段名也作为参数输入
User selectUserByParameter(Map<String, String> map);
复制代码
<select id="selectUserByParameter" parameterType="map" resultType="user">
    select id, name, address
    from user
    where ${type} = #{content};
</select>
复制代码
  @Test
  public void selectUserByParameterTest() {
    try (SqlSession sqlSession = Utils.getSqlSession()) {
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      Map<String, String> map = new HashMap<>();
      //map.put("type", "name");
      //map.put("content", "杜甫");
      map.put("type", "id");
      map.put("content", "3");
      User user = mapper.selectUserByParameter(map);
      System.out.println(user);
    }
  }
复制代码

这种方法,玩玩就好,不安全。同样的,会SQL注入。

六、结果映射(resultMap)

  • 当出现Java Bean和表的字段名不一样的情况时,有两种解决方法:取别名、使用结果映射
  • Java Bean
// 利用lombok直接生成那些固定的方法
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
  int id;
  String lastName;
  String firstName;
}
复制代码
  • 数据库的表
CREATE TABLE person(
        id 			INT 		PRIMARY KEY AUTO_INCREMENT,
        last_name 	VARCHAR(20)	NOT NULL,
        first_name 	VARCHAR(20)	NOT NULL
)ENGINE=INNODB ;
复制代码
  • 取别名
select id, last_name AS lastName, first_name AS firstName
from person;
复制代码
  • 结果映射
<!--修改成对应的接口-->
<mapper namespace="com.du.mybatis.dao.PersonMapper">
    <!-- id为该resultMap的唯一标识,用于后续引用   -->
    <!-- type为指定类,可以使用别名 -->
    <resultMap id="personResultMap" type="person">
        <id property="id" column="id"/>
        <result property="lastName" column="last_name"/>
        <result property="firstName" column="first_name"/>
    </resultMap>
    
    <!--  resultMap用来选择指定的结果映射  -->
    <select id="getPersons" resultMap="personResultMap">
        select id, last_name, first_name
        from person;
    </select>
</mapper>
复制代码
  • 结果映射的各个属性
属性 描述
constructor 用于在实例化类时,注入结果到构造方法中
id 一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能
result 注入到字段或 JavaBean 属性的普通结果
association 一个复杂类型的关联;许多结果将包装成这种类型
collection 一个复杂类型的集合
discriminator 使用结果值来决定使用哪个 resultMap
case 基于某些值的结果映射
  • id&result
    • id 和 result 元素都将一个列的值映射到一个简单数据类型(String, int, double, Date 等)的属性或字段。
    • 这两者之间的唯一不同是,id 元素对应的属性会被标记为对象的标识符,在比较对象实例时使用。 这样可以提高整体的性能,尤其是进行缓存和嵌套结果映射(也就是连接映射)的时候

七、关联

7.1 嵌套select查询

  • 嵌套 Select 查询:通过执行另外一个 SQL 映射语句来加载期望的复杂类型(简单来说,就是两个select语句嵌套)
@Data
public class Teacher {
  private String name;
  private int id;
}
复制代码
@Data
public class Student {
  private int id;
  private Teacher teacher;
  private String name;
}
复制代码

而database中只存放了老师的id,并没有存放老师。因此需要通过id查询老师,并返回给Student

<!-- 根据id查找一个老师   -->
<select id="getTeacher" resultType="teacher" parameterType="_int">
    select *
    from teacher
    where id = #{id};
</select>
复制代码

首先通过一个简单的select语句,通过id查询出指定的老师

<!--getStudents的resultMap-->
<resultMap id="studentResultMap" type="student">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <!--  column作为输入,到getTeacher中查找   -->
    <association property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>
复制代码

然后在resultMap中,通过association进行select关联。
property为java bean的属性名,column为数据库表中的列名称,javaType为该关联映射的java bean,select为用于查询该java bean的接口

<select id="getStudents" resultMap="studentResultMap">
    select *
    from student;
</select>
复制代码

最后通过一个resultMap作为参数即可

7.2 嵌套结果映射

  • 嵌套结果映射:使用嵌套的结果映射来处理连接结果的重复子集(其实就是通过两个表联结来处理)
<resultMap id="studentResultMap" type="student">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" javaType="teacher">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
    </association>
</resultMap>
复制代码

通过结果映射,结果输出一个Student类。在里面通过association,嵌套查询Teacher

<select id="getStudents" resultMap="studentResultMap">
    select *
    from student, teacher
    where student.tid = teacher.id;
</select>
复制代码

八、集合

  • 集合,即一对多,一个java bean有一个属性,由另一个java bean的集合组成。需要通过sql查询出来。基本思路与上面相同,基本有两种方法:嵌入子查询、连表查询
  • java bean
@Data
public class Student {
  private int id;
  private String name;
  private int tid;  // 对应的Teacher id
}
复制代码
@Data
public class Teacher {
  private String name;
  private int id;
  private List<Student> students;   // 集合
}
复制代码

8.1 集合的嵌套 Select 查询

<select id="selectStudentsByTId" resultType="Student" parameterType="_int">
    select *
    from student
    where tid = #{tid};
</select>

<select id="selectTeacherById" resultMap="selectTeacherByIdResultMap" parameterType="_int">
    select *
    from teacher
    where id = #{id};
</select>

<resultMap id="selectTeacherByIdResultMap" type="Teacher">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="students" select="selectStudentsByTId" javaType="ArrayList" ofType="student" column="id"/>
</resultMap>
复制代码
  • 基本思路:查出所有tid为tid的学生,再查出指定id的老师的信息,通过resultMap映射出结果。
  • resultMap就是用来解析sql查出来的结果的,一一对应的关系可直接不写。对于集合来说,需要使用到collection属性,property为java bean的属性,column为sql中查出来的某一列的名字,javaType为该属性的类型,ofType为该集合的泛型类型,select为该属性的查询语句。

8.2 集合的嵌套结果映射

<select id="selectTeacherById" resultMap="selectTeacherByIdResultMap" parameterType="_int">
select s.id sid, s.NAME sname, t.id t_id, t.name tname
from teacher t,
     student s
where t.id = s.tid
  and t.id = #{id};
</select>

<resultMap id="selectTeacherByIdResultMap" type="teacher">
<result column="tid" property="id"/>
<result column="tname" property="name"/>
<collection property="students" ofType="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <result property="tid" column="t_id"/>
</collection>
</resultMap>
复制代码
  • 基本思想为:通过一个连表查询出结果之后,对结果进行一个处理。一一对应的属性可以忽略,不是一一对应的关系,就用一个collection接收处理结果。collection里面也用result接收结果。
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享