商品分类里有家用电器,家用电器也有多个分类
数据库里的parent_id引用了本表的id字段
实体类
package com.yq.cn.dao.entity;
import java.util.Set;
public class Category {
private Long id;
private String name;
private Long parentId;
private Set<Category> children;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public Set<Category> getChildren() {
return children;
}
public void setChildren(Set<Category> children) {
this.children = children;
}
}
resultMap为
<resultMap id="childResultMap" type="com.yq.cn.dao.entity.Category">
<id column="pid" property="id" jdbcType="BIGINT" />
<result column="pname" property="name" jdbcType="VARCHAR" />
<collection property="children" ofType="com.yq.cn.dao.entity.Category">
<id column="cid" property="id" jdbcType="BIGINT" />
<result column="cname" property="name" jdbcType="VARCHAR" />
</collection>
</resultMap>
sql语句为
<select id="listAll" resultMap="childResultMap">
SELECT t.`id` pid,t.`name` pname,t2.`id` cid,t2.`name` cname
FROM tbl_category t,tbl_category t2
WHERE t.id=t2.parent_id
</select>