单表查询
作用:
在数据库中命名字段名的时候经常会使用到下划线 "_",然而在实体类中往往不写下划线,所以可以使用mybatis对其进行封装
注意:
resultMap的id要与select语句中的resultMap相对应
property为实体类表中的字段名字,column为数据库中的字段名
示例:
<resultMap id="DeptMap" type="Dept">
<id property="id" column="id"></id>
<result property="dname" column="d_name"></result>
<result property="loc" column="loc"></result>
</resultMap>
<select id="selectAll" resultMap="DeptMap">
select * from dept
</select>
多表查询
一对一
示例:
现在有Card和Person两个实体类
public class Card {
private int id;
private String number;
private int pid;
private Person p;
}
public class Person {
private int id;
private String name;
private int age;
}
现在对这两个表进行一对一查询
注意:
resultMap的id要与select语句中的resultMap相对应
property为实体类表中的字段名字,column为数据库中的字段名
一对一:在resultMap下添加person中封装的对象,使用association进行封装,association(一对一)中的property属性的值为person中封装的对象
示例:
<mapper namespace="com.chen.mapper.CardMapper">
<resultMap id="One" type="com.chen.pojo.Card">
<id property="id" column="id" ></id>
<result property="number" column="number"></result>
<result property="pid" column="pid"></result>
<association property="p" javaType="com.chen.pojo.Person">
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="age" property="age"></result>
</association>
</resultMap>
<select id="findAll" resultMap="One">
select person.name,person.age,card.number
from card,person
where card.pid=person.id
</select>
</mapper>
一对多
联合的表:
Classes中需要有Student的对象
private Student students;
示例:
Classes类:
public class Classes {
private Integer id;
private String name;
private Student students;
}
Student类
public class Student {
private Integer id;
private String name;
private Integer age;
private Integer cid;
}
注意:
resultMap的id要与select语句中的resultMap相对应
property为实体类表中的字段名字,column为数据库中的字段名
在resultMap下的property属性的值为Classes中封装的对象,collection下的是Student类中封装的对象,一对多使用collection进行封装,
示例:
<mapper namespace="com.chen.mapper.ClassesMapper">
<resultMap id="OneToMany" type="com.chen.pojo.Classes">
<id property="id" column="id" ></id>
<result property="name" column="name"></result>
<collection property="students" javaType="com.chen.pojo.Student">
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="age" property="age"></result>
<result column="cid" property="cid"></result>
</collection>
</resultMap>
<select id="selectBy" resultMap="OneToMany">
SELECT s.`id`,s.`NAME`,s.`age`,c.`id`,c.`NAME`
FROM classes c,student s
WHERE s.`cid`=c.`id`
AND s.`NAME`=#{name}
</select>
</mapper>