2017-04-13 58 views
0

我有這種情況;
Postgres的表:Hibernate Example.create不能使用@EmbeddedId

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(); 

我希望像的查詢
SELECT * FROM seguaci其中id_folloee = '斯特凡諾' 和attivo = TRUE;
但是,我獲得其中

where (this_.attivo=?) 

回答

0

Hibernate文檔states該查詢通過示例(QBE)忽略主鍵中只有一個條件:

版本屬性,標識符和關聯是忽略。通過 默認值,排除空值屬性。

您需要添加標識限制手動。新增(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();