Hibernate Example.create不适用于@EmbeddedId

时间:2017-04-13 10:02:20

标签: java postgresql hibernate orm

我有这种情况;
Postgres表:

   Colonna   |         Tipo          | Modificatori 
-------------+-----------------------+--------------
 id_followee | character varying(20) | non null
 id_follower | character varying(20) | non null
 attivo      | boolean               | 
 valutazione | boolean               | non null
Indici:
    "seguaci_pkey" PRIMARY KEY, btree (id_followee, id_follower)

因此,我以这种方式创建了一个使用@EmbeddedId的pojo类:

@Embeddable
public class SeguaciId implements java.io.Serializable {
    // Fields
        @Column(name = "id_followee", nullable = false, length = 20)
    private String idFollowee;
    @Column(name = "id_follower", nullable = false, length = 20)
    private String idFollower;
}

@Entity
@Table(name = "seguaci", schema = "public")
public class Seguaci extends Pojo implements java.io.Serializable {

    // Fields
    private static final long serialVersionUID = -1862253468007580073L;
    @EmbeddedId
    @AttributeOverrides({
            @AttributeOverride(name = "idFollowee", column = @Column(name = "id_followee", nullable = false, length = 20)),
            @AttributeOverride(name = "idFollower", column = @Column(name = "id_follower", nullable = false, length = 20)) })
    private SeguaciId id; // not null
    @Column(name = "attivo")
    private Boolean attivo;
    @Column(name = "valutazione", nullable = false)
    private Boolean valutazione; // not null
}

此时,我注意到了方法

org.hibernate.criterion.Example.create()   

不考虑嵌入对象中输入的值 例如

SeguaciDAO dao = new SeguaciDAO();
    Seguaci se = new Seguaci();
    se.setAttivo(true);
    SeguaciId id = new SeguaciId();
    id.setIdFollowee("stefano");
    se.setId(id);

// end call this method
List<Seguaci> results = this.getSession().createCriteria(Seguaci.class)
                    .add( Example.create(instance) )
                    .list();

我希望有一个类似的查询 从seguaci中选择*,其中id_folloee ='stefano'和attivo = true;
但是,我只在其中获得了一个条件

where (this_.attivo=?)

1 个答案:

答案 0 :(得分:0)

按示例查询的Hibernate文档states(QBE)忽略主键:

  

忽略版本属性,标识符和关联。通过   默认情况下,排除了空值属性。

您需要使用 .add(Restrictions.eq(...))添加标识符限制手动

List<Seguaci> results = this.getSession().createCriteria(Seguaci.class)
                    .add( Example.create(instance) )
                    .add(Restrictions.eq("id.idFollowee", "stefano"))
                    .add(Restrictions.eq("id.idFollower", "Pierock"))
                    .list();