所谓自关联是指,自己即充当一方,又充当多方。其实就是普通1:n 和 n:1的变形
1、一对多
1)表结构
-- 新闻栏目
CREATE TABLE `news` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
`pid` int(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2)实体类
// 新闻栏目:当前的新闻栏目被看作是一方,即父栏目
public class News {
private Integer id;
private String name;
private Set<News> childen;
//省略get set属性方法
@Override
public String toString() {
return "News [id=" + id + ", name=" + name + ", childen=" + childen
+ "]";
}
}
3)Dao接口
public interface INewsDao {
List<News> selectById(int id);//查询指定id栏目下面的所有子孙菜单
News selectById2(int id);//查询指定id栏目及下面的所有子孙菜单
}
4)mapper.xml文件
<!-- 查询指定id栏目下面的所有子孙菜单 -->
<resultMap type="News" id="newsMapper">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="childen"
ofType="News"
select="selectById"
column="id"/>
</resultMap>
<select id="selectById" resultMap="newsMapper">
select id,name from news where pid = #{xxx}
</select>
<!-- 查询指定id栏目 及 下面的所有子孙菜单 -->
<select id="selectChilden" resultMap="newsMapper">
select id,name from news where pid=#{ooo}
</select>
<resultMap type="News" id=