`

hibernate 级联查询

    博客分类:
  • Java
阅读更多

hibernate级联查询

1,实体类结构

@Entity
@Table(name = "t_vote")
public class Vote {
	private int id;
	/***
	 * 1:最宜居<br>
	 * 2:最优户<br>
	 * 3:最佳物业
	 */
	private int type;
	private HouseBuilding houseBuilding;
	/***
	 * 投票数
	 */
	private long voteCount;
@OneToOne
	@JoinColumn(name = "house_building_id")
	public HouseBuilding getHouseBuilding() {
		return houseBuilding;
	}
}

 

@Entity
@Table(name = "t_house")
public class HouseBuilding {
	private int id;
	private String name;
	private String address;
	private Float price;
	/***
	 * 预留
	 */
	private String reserved;
}

 

 

 

2,关系

Vote和HouseBuilding 是一对一的外键关系,从Vote 可以导航到HouseBuilding,反之不能.

 

3,查询语句(实例)

Vote vote=super.get("type", type,"houseBuilding.id",houseBuildingId);

 super.get 方法体如下:

public T get(String propertyName,Object propertyValue,String propertyName2,Object propertyValue2){
		return (T)this.getCurrentSession().createCriteria(clz)
				.add(Restrictions.eq(propertyName, propertyValue))
				.add(Restrictions.eq(propertyName2, propertyValue2))
				.uniqueResult();
	}

 所以实际上相当于:

Vote vote=(Vote) super.getCurrentSession().createCriteria(clz)
		.add(Restrictions.eq("type", type))
		.add(Restrictions.eq("houseBuilding.id",houseBuildingId))
		.uniqueResult();

 

类似于:

Vote vote=(Vote) super.getCurrentSession().createCriteria(clz)
		.add(Restrictions.eq("type", type))
		.createAlias("houseBuilding", "houseBuilding222")
		.add(Restrictions.eq("houseBuilding222.id", houseBuildingId))
		.uniqueResult();

 

 

4,执行的SQL 语句

select
        this_.id as id1_21_1_,
        this_.house_building_id as house4_21_1_,
        this_.type as type2_21_1_,
        this_.vote_count as vote3_21_1_,
        housebuild2_.id as id1_9_0_,
        housebuild2_.address as address2_9_0_,
        housebuild2_.name as name3_9_0_,
        housebuild2_.price as price4_9_0_,
        housebuild2_.reserved as reserved5_9_0_ 
    from
        t_vote this_ 
    left outer join
        t_house housebuild2_ 
            on this_.house_building_id=housebuild2_.id 
    where
        this_.type=? 
        and this_.house_building_id=?
07 十月 2015 10:04:22,589 TRACE org.hibernate.type.descriptor.sql.BasicBinder:84 - binding parameter [1] as [INTEGER] - 1
07 十月 2015 10:04:22,590 TRACE org.hibernate.type.descriptor.sql.BasicBinder:84 - binding parameter [2] as [INTEGER] - 3

 

 

5,使用Restrictions.eq 来进行条件查询时,第一个参数可以采用"属性.子属性"的形式

6,在单元测试中,加载hibernate配置文件

@BeforeClass
	public static void before() {
		ctx = new ClassPathXmlApplicationContext("beans.xml");
//		clientVersionDao = (ClientVersionDao) ctx.getBean("clientVersionDao");
//		oSVersionDao = (OSVersionDao) ctx.getBean("osVersionDao");
//		osTypeDao = (OsTypeDao) ctx.getBean("osTypeDao");
		paperNewsDao = (PaperNewsDao) ctx.getBean("paperNewsDao");
		voteDao = (VoteDao) ctx.getBean("voteDao");
	}

 

7,源代码

上述代码中的super指com.common.dao.generic.GenericDao ,详见附件

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics