所谓自关联,是指,自己既充当一的一方,又充当多的一方,是1:n或n:1的变型。
实体类:
package com.mybatisdemo.beans; import java.util.ArrayList; import java.util.List; public class News { private Integer id; private String name; private List<News> newsChild = new ArrayList<>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<News> getNewsChild() { return newsChild; } public void setNewsChild(List<News> newsChild) { this.newsChild = newsChild; } @Override public String toString() { return "News [id=" + id + ", name=" + name + ", newsChild=" + newsChild + "]"; } }
Dao层对应的映射文件Mapper
<?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.mybatisdemo.dao.NewsDao"> <resultMap type="com.mybatisdemo.beans.News" id="newsMapper"> <id column="id" property="id"/> <result column="name" property="name"/> <!-- 这边因为是根据父id来查的,所以传入的是id --> <collection property="newsChild" column="id" ofType="com.mybatisdemo.beans.News" select="queryNewsByPId"/> </resultMap> <!-- 根据父id来查子列表 --> <select id="queryNewsByPId" parameterType="int" resultMap="newsMapper"> select id,name,pid from news where pid = #{id} </select> </mapper>
测试类:
@Test public void testNews() { NewsDao newsDao = sqlSession.getMapper(NewsDao.class); List<News> newsList = newsDao.queryNewsByPId(2); System.out.println(newsList); }
PS:数据库表结构
create table if not exists news( id int(10) not null primary key, name varchar(25) not null, pid int(10) ) charset utf8;