日期:2014-05-17  浏览次数:20777 次

hibernate 关系配置
最近在学习java的资料,使用hibernate有个问题,请教大家。
===1.表结构========
  A:表(1的关系)
  ----Aid----Aname
  B:表(N的关系)
  ----Bid----Aid----Bname---Btype(类型)
===2.建立O/R=======
  A:表
  Set关系(到B表)
  省略(其他setter与getter...)
  B:表
  省略(其他setter与getter...)
===3.查询==========
  1.查询A表记录。简单 Quert.createQuery("form A").List();
  2.查询A表记录及每个记录下B的
  即 select a.aid,count(1) from a left join b on a.aid = b.aid where b.btype=1 group by a.aid
  那么这样应该怎么去配置。(主要是 1.where b.btype=1 2.group by a.aid)
  
  请问怎么配置对应sql关系呢??

------解决方案--------------------
这样配好像有问题
hibernate一对多应该这样配
class A {
private Integer aId;
private String aName;
private Set <B> setB;
set..get..

class B{
private Integer bId;
private String bName;
private A a;
set..get..
}

hql:from A得到A的List后
for(A a :listA){
a.getSetB();//就得到每条A下的B了

------解决方案--------------------
A表的配置设置好cascade就好了啊,查询A的同时会级联B
------解决方案--------------------
这是“单向不使用联接表的多对一关联”,详情查看hibernate手册
大致说一下
首先orm
B类不是用String aId
而是 private A a
然后mapping里,<many-to-one name="a" column="aid" />
select a.id,count(1) from b where btype=1 group by a.id
这样b里就关联了a了
够详细了吧,给分吧
------解决方案--------------------
既然建立了关联,那么查询A表的数据时,A表中对应的B的Set肯定是可以获取的,那么LZ的关联查询又有什么意义呢?还有设置set的casecode=“select”查询时级联更新,再需要注意的一个问题就是不要延迟加载。。。