1.一对一查询:
根据角色来查询所对应的people,这里是通过age来关联两个表的。
需求:根据role 的age_id来查询对应的people
实现:因为它们关联的字段是age,在xml文件做一对一映射使用association映射age所对应的实体类即可。
role pojo:
package com.shuai.pojo;
import lombok.Data;
@Data
public class Role {
private String workNmame;
private People people;
}
mapper xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shuai.mapper.PeopleMapper">
<resultMap id="RoleMapper" type="com.shuai.pojo.Role">
<result property="workNmame" column="work_name"></result>
<association property="people" javaType="com.shuai.pojo.People">
<result property="name" column="name"></result>
<result property="age" column="age"></result>
</association>
</resultMap>
<select id="findById" resultMap="RoleMapper" parameterType="int" >
select * from people,role where people.age=role.age_id and age_id=#{id};
</select>
</mapper>
2.一对多查询:一对多基于一对一的基础上的,只是对于age的映射改成关于实体类的集合,association改为collection做相关映射。
role
package com.shuai.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Role {
private String workNmame;
private List<People> people;
}
mapper xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shuai.mapper.PeopleMapper">
<resultMap id="RoleMapper" type="com.shuai.pojo.Role">
<result property="workNmame" column="work_name"></result>
<collection property="people" ofType="com.shuai.pojo.People">
<result property="name" column="name"></result>
<result property="age" column="age"></result>
</collection>
</resultMap>
<select id="findById" resultMap="RoleMapper" parameterType="int" >
select * from people,role where people.age=role.age_id and age_id=#{id};
</select>
</mapper>
网友评论