Hibernate:具有多对多连接表的条件? [英] Hibernate: Criteria with many-to-many join table?

查看:132
本文介绍了Hibernate:具有多对多连接表的条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下两个关系:

pre $ @Entity class Foo {
@Id id;
$ b @ManyToMany
@JoinTable(name =ATag,
joinColumns = @JoinColumn(name =foo_id),
inverseJoinColumns = @JoinColumn(name = tag_id))
设置< Tag>标签;
}

@实体类标记{
@Id Long id;
字符串名称;
}

连接表ATag没有相应的实体类。现在,我想获得所有名为'tag1'的Tag的Foo实例,是否可以仅使用Criteria?



子查询可能有帮助,但是,为类ATag.class创建DetachedCriteria,它不存在。

解决方案

刚处理完这个问题。你在考虑表格,而不是对象。只需引用 tags.name ,然后让Hibernate处理其余部分:

  Criteria crit = session.createCriteria(Foo.class); 
crit.createAlias(tags,tagsAlias);
crit.add(Restrictions.eq(tagsAlias.name,someValue);

如果你看到SQL Hibernate吐出来了,你会发现它使用了连接表。


Consider following two relations:

@Entity class Foo {
    @Id id;

    @ManyToMany
    @JoinTable(name = "ATag", 
         joinColumns = @JoinColumn(name = "foo_id"),
         inverseJoinColumns = @JoinColumn(name = "tag_id"))
    Set<Tag> tags;
}

@Entity class Tag {
    @Id Long id;
    String name;
}

There is no corresponding entity class for the join table ATag. Now, I want to get all Foo instances with Tag named 'tag1', is it possible using only Criteria?

A sub-query maybe helpful, however, I can't create DetachedCriteria for class ATag.class which isn't existed.

解决方案

Just dealt with this exact issue. You're thinking in tables, not objects. Just reference tags.name and let Hibernate take care of the rest:

Criteria crit = session.createCriteria(Foo.class);
crit.createAlias("tags", "tagsAlias");
crit.add(Restrictions.eq("tagsAlias.name", someValue);

If you watch the SQL Hibernate spits out, you'll see it uses the join table.

这篇关于Hibernate:具有多对多连接表的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆