MyBatis一对多、多对一结果集映射
一对一关系
eg:一个学生对应一张学生卡,学生信息作为一个表,学生卡作为一个表,通过id列联结
StudentPojo
public class StudentPojo {
private int id;
private String name;
private Card card;
省略setter、getter
}
CardPojo
public class CardPojo {
private int id;
private String addr;
private int idNum;
省略setter、getter
}
XML配置
这里需要用到一个标签:<association>
<association property="card" javaType="dream.mybatis.CardPojo">...</association>
- property - pojo类对应的字段名(例如StudentPojo的card字段)
- column - 用于联结的列
- javaType - pojo类的完全限定名 (例如 xxx.xxx.CardPojo)
<mapper namespace="UserMapper">
<resultMap id="studentMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="card" javaType="dream.mybatis.CardPojo">
<id property="id" column="id"/>
<result property="addr" column="addr"/>
<result property="idNum" column="id_num"/>
</association>
</resultMap>
<select id="selectStu" resultMap="studentMap">
select * from students left outer join card on students.id=card.id
</select>
</mapper>
这里的mapper与上面的两个pojo类一一对应,resultMap包含的属性对应StudentPojo的字段,association就是StudentPojo类中的card字段,由于card是一个对象,所以association中又包含了这个对象的字段
java实现
public class MyBatisTest {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSession session=new SqlSessionFactoryBuilder().build(is).openSession();
List<User> list=session.selectList("UserMapper.selectStu");
list.iterator().forEachRemaining(e-> System.out.println(e.toString()));
}
}
这里就将学生与学生卡的信息联结起来,一起打印出来了
多对一关系
eg:一个班级有多个学生,班级信息作为一个表,学生信息作为一个表,学生表的class_id列对应班级表的id列
ClassPojo
public class ClassPojo {
private int id;
private int name;
private ArrayList<Student> students;
省略setter、getter
}
StudentPojo
public class StudentPojo {
private int studentId;
private int classId;
private String studentName;
省略setter、getter
}
XML配置
这里需要用到 <collection>
<collection property="students" ofType="Student">
- property - 在pojo中对应的字段名
- column - 用于联结的列
- ofType - 集合中的元素类型,一对多的结果通常由一个List存储,就像ClassPojo中的students字段,这个属性即是List中存储的元素类型
<resultMap id="moreToOne" type="ClassPojo">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" ofType="Student">
<result property="studentId" column="student_id"/>
<result property="studentName" column="student_name"/>
<result property="age" column="age"/>
<result property="classId" column="class_id"/>
</collection>
</resultMap>
<select id="classAndStudent">
select * from class left outer join students on class.id=students.class_id;
<!-- 如果表中有同名的列,那么这个列一定要使用别名,否则多个同名的列只能获取到一个列的结果-->
</select>
java中实现
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSession session=new SqlSessionFactoryBuilder().build(is).openSession();
List<ClassPojo> list=session.selectList("selectMapper.more");
list.iterator().forEachRemaining(e -> System.out.println(e.toString()));
}