Mybatis学习二(字段名与实体类属性名不相同/关联查询)

1.在写项目的时候会遇到数据库字段名与实体类属性名不同的情况,可能是为了方便也可能是其他要求,whatever,我们现在来解决这个问题

准备一个数据库表如下

1 CREATE TABLE orders(
2   order_id INT PRIMARY KEY AUTO_INCREMENT,
3   order_no VARCHAR(20),
4   order_price FLOAT
5 );

接下类定义一个实体类

1 public class Order {
2     private int id;
3     private String orderNo;
4     private float price;
5 }

可见我们定义的实体类与数据库表字段名不一致,对于此有两种解决方法

方法一:在 sql 语句中定义别名

1 <select id="selectOrder" parameterType="int" resultType="_Order">
2     select order_id id, order_no orderNo,order_price price from orders where order_id=#{id}
3 </select>

方法二:通过<resultMap>解决

<select id="selectOrderResultMap" parameterType="int" resultMap="orderResultMap">
     select * from orders where order_id=#{id}
</select>
<resultMap type="_Order" id="orderResultMap">
    <id property="id" column="order_id"/>
    <result property="orderNo" column="order_no"/>
    <result property="price" column="order_price"/>
</resultMap>

例如(其中涉及到了嵌套(association)结果的关联查询,接下来会解释它)

 2.实现联表查询

定义实体类

teacher实体类

private int tId;
private String tName;

student实体类

private int sId;
private String sName;
private int ClassId;

clazz实体类

private int cId;
private String cName;
private int tId;
private Teacher teacher;
private List<Student> students;

其中clazz实体类中,一个班级对应一个老师,一个班级对应多个学生

此时的ClazzMapper.xml映射文件如下

 对于一对多,多对一问题我们可以有两种解决方法

方法一:二次查询

方法二:联表查询

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 <!-- namespace:表示名称空间。现在的目的是区分id的. -->
 5 <mapper namespace="com.zhiyou100.zhl.dao.ClazzDao">
 6     <resultMap type="com.zhiyou100.zhl.bean.Clazz" id="mymap">
 7         <id column="c_id" property="cId"/>
 8         <result column="c_name" property="cName"/>
 9         <result column="teacher_id" property="tId"/>
10         <association property="teacher" javaType="com.zhiyou100.zhl.bean.Teacher">
11             <id column="t_id" property="tId"/>
12             <result column="t_name" property="tName"/>
13         </association>
14         <collection property="students" ofType="com.zhiyou100.zhl.bean.Student">
15             <id column="s_id" property="sId"/>
16             <result column="s_name" property="sName"/>
17         </collection>
18     </resultMap>
19     
20     <select id="selectById" resultMap="mymap">
21         select * from class c join teacher t join student s on c.teacher_id=t.t_id and s.class_id=c.c_id where c_id=#{cId};
22     </select>
23     
24 </mapper>

进行单元测试

原文地址:https://www.cnblogs.com/murmansk/p/11442856.html