您的位置:首页 > 其它

Hibernate的Join

2012-01-07 14:24 141 查看
连接

1. 两种join方式
ansi-style: t1 left join t2 on t1.id=t2.id
theta-style: t1,t2 where t1.id=t2.id

2. hibernate通常不用显式声明连接条件,在hbm中有足够的信息,四种join方式:
from声明的一般的join
from声明的fetch join
where中指定的theta-style:可以用于不含关联关系得两张表
隐式join

3. fetching association
bids也会在这个sql中全部查出来:
from Item item
left join fetch item.bids
where item.description like '%gc%'
Criteria:
session.createCriteria(Item.class)
.setFetchMode("bids", FetchMode.EAGER)
.add(Expression.like("description", "gc", MatchMode.ANYWHERE))
.list;
注意:
HQL会忽略映射文件中的out-join配置,但Criteria不会
限制之查询一个collection,将来版本可能放松限制
可能会查出多个数据库的同一记录:bid left join item,item会重复

4. 在join中使用别名
非fetch会返回Object[],可以通过select t1来限制返回对象:
from Item item join item.bids bid 返回List<object{Item.class, Bid.class}>
select item from Item item join item.bids bid 返回List<Item>

5. 隐式join
from User u where u.address.city = 'Bangkok'

6. Theta-style joins
from User user, LogRecord log where user.username = log.username
criteria不支持:criteria不支持两个没有关联的表做out-join

7. 比较字段
hbm有关联关系,使用外键:from Item i, User u where i.seller = u and u.username = 'steve'
没有关联关系,等同上面的:from Item i, User u where i.seller.id = u.id and u.username = 'steve'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: