搜索多个标记的文章 - Hibernate多对多

时间:2011-04-27 03:22:30

标签: hibernate many-to-many

我存储多个标签的文章如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Article {

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToMany
    private List<Tag> tags;

    private String subject;

}

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Tag {

    @Id
    private String name;

    private String description;

}

我想搜索包含某些标签的文章,例如,问题hibernatemany-to-many。所以我试着:

import static org.hibernate.criterion.Restrictions.*;

// ...

Criteria criteria = session.createCriteria(Article.class);
Criteria tagCriteria = criteria.createCriteria("tags");
tagCriteria.add(and(eq("name", "hibernate"), eq("name", "many-to-many")));

@SuppressWarnings("unchecked")
List<Article> list = criteria.list();

但是,不起作用,返回的列表为空,因为记录的SQL显示为:

select 
    this_.id as id1_1_, 
    this_.subject as subject1_1_, 
    tags3_.Article_id as Article1_, 
    tag1_.name as tags2_, 
    tag1_.name as name0_0_, 
    tag1_.description as descript2_0_0_ 
from 
    Article this_ 
    inner join Article_Tag tags3_ on this_.id=tags3_.Article_id 
    inner join Tag tag1_ on tags3_.tags_name=tag1_.name 
where 
    tag1_.name=? // assign 'hibernate'
    and 
    tag1_.name=? // assign 'many-to-many'

and替换为or时返回的文章太多,因为生成的SQL为... where (tag1_.name=? or tag1_.name=?)

我想要的确切看起来像:

select 
    this_.id as id1_1_, 
    this_.subject as subject1_1_, 
    tags3_.Article_id as Article1_, 
    tag1_.name as tags4_, 
    tag1_.name as name0_0_, 
    tag1_.description as descript2_0_0_ 
from 
    Article this_ 
    inner join Article_Tag tags3_ on this_.id=tags3_.Article_id 
    inner join Tag         tag1_  on tags3_.tags_name=tag1_.name 
    // following 2 lines are added
    inner join Article_Tag tags4_ on this_.id=tags4_.Article_id 
    inner join Tag         tag5_  on tags4_.tags_name=tag5_.name 
where 
    tag1_.name=? // assign 'hibernate'
    and
    tag5_.name=? // assign 'many-to-many'

我只能使用HQL吗?

1 个答案:

答案 0 :(得分:1)

你应该尝试类似的东西:

    Criteria criteria = getSession().createCriteria(Article.class);
    int i=0;
    for ( String tagName : tagNames ) {
        String aliasName = "alias_" + i;
        criteria.createAlias("tags", aliasName, Criteria.INNER_JOIN);
        criteria.add( Restrictions.eq(aliasName+".name",tagName) );
        i++;
    }

实际上问题在于,当你做一个简单的内连接时,你可以用标签加入你的结果,但问题是数据实际上是2行...所以如果你加入2次你会是能够获取一行数据。

我认为这不是很优雅,但应该有用......