基于注解自身OneToMany

直接看代码:
package net.mai123.bean;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="TYPE_INF")
public class TypeInf {
	@Id
	@Column(name="TYPE_ID")
	private int    typeId;
	
	@Column(name="TYPE_NAME")
	private String typeName;
	

	@Column(name="PARENT_ID")
	private int parentId;
	
	@OneToMany(targetEntity=TypeInf.class)
	@JoinColumn(name="PARENT_ID")
	private List<TypeInf>  childrens;
	
	@Column(name="SHOWABLE")
	private int    showAble;
	
	@Column(name="REMARK")
	private String remark;
	public int getTypeId() {
		return typeId;
	}
	/************* 省略掉setter和getter **************/
}


对应的数据库表结构
DROP TABLE IF EXISTS TYPE_INF;
CREATE TABLE TYPE_INF(
	TYPE_ID   INT AUTO_INCREMENT PRIMARY KEY,
	TYPE_NAME VARCHAR(40),
	PARENT_ID INT,
	SHOWABLE  INT DEFAULT 0,
	REMARK    VARCHAR(400)
);

DAO类
package net.mai123.dao.impl;

import java.util.List;

import net.mai123.bean.TypeInf;

public class TypeInfDao extends CommonDao<TypeInf> {

	/************* 省略掉无关的代码 **************/

	@SuppressWarnings("unchecked")
	public List<TypeInf> doQuery() {
		//加上select distinct是为了去除重复的parent
		//left join fetch 可以不延迟加载
		List<TypeInf> lst = find("select distinct t from TypeInf t left join fetch t.childrens where t.parentId=0");
		for(TypeInf t : lst){
			System.out.println(t.getTypeName()+":"+t.getChildrens().size());
		}
		return lst;
	}

	
}


这样就OK乐。。看下打印的SQL和结果
Hibernate: 
    select
        distinct typeinf0_.TYPE_ID as TYPE1_1_0_,
        childrens1_.TYPE_ID as TYPE1_1_1_,
        typeinf0_.PARENT_ID as PARENT2_1_0_,
        typeinf0_.REMARK as REMARK1_0_,
        typeinf0_.SHOWABLE as SHOWABLE1_0_,
        typeinf0_.TYPE_NAME as TYPE5_1_0_,
        childrens1_.PARENT_ID as PARENT2_1_1_,
        childrens1_.REMARK as REMARK1_1_,
        childrens1_.SHOWABLE as SHOWABLE1_1_,
        childrens1_.TYPE_NAME as TYPE5_1_1_,
        childrens1_.PARENT_ID as PARENT2_0__,
        childrens1_.TYPE_ID as TYPE1_0__ 
    from
        TYPE_INF typeinf0_ 
    left outer join
        TYPE_INF childrens1_ 
            on typeinf0_.TYPE_ID=childrens1_.PARENT_ID 
    where
        typeinf0_.PARENT_ID=0

家具/日用品:6
二手笔记本:13
电子数码:6
图书/音乐/运动 :5
家用电器:9
台式电脑/网络:4
服饰/箱包/化妆品:6
商用/办公:4
闲置礼品:3
手机/通讯相关:5
母婴/儿童用品:5


好了。。childrens加载进来了。。而且也parent也不会重复。。。
搞了半天。。哎

你可能感兴趣的:(DAO,sql,bean,Hibernate,音乐)