2017-02-12 67 views
1

薩拉姆,搜索鍵值實體

我有一個(鍵,值)實體搜索的問題。

我不知道如何寫JPQL查詢搜索..這是我的問題

我已經文檔實體,映射到一對多「元數據」實體

@Entity 
public class Document implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @Column(name="id_document") 
    private Integer idDocument; 

    @Column(name="date_enregistrement") 
    private Timestamp dateEnregistrement; 

    // other columns 

    //bi-directional many-to-one association to MetaData 
    @OneToMany(mappedBy="document") 
    private List<MetaData> metaData; 

    /* 
    getters and setters 
    */ 
} 

和元數據實體

@Entity 
@Table(name="meta_data") 
public class MetaData implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @Column(name="id_meta_data") 
    private Integer idMetaData; 

    @Column(name="key") 
    private String key; 

    @Column(name="value") 
    private String value; 

    //bi-directional many-to-one association to Document 
    @ManyToOne 
    @JoinColumn(name="id_document") 
    private Document document; 

    /* 
    getters and setters 
    */ 

} 

我想要做的是通過提供一些元數據作爲參數來搜索文檔。

例子:

查找文件,其中發送者(標號=發送者)是優素福(值=優素福)和接收機(密鑰)是哈姆扎(值)

它可能是在客戶端提供兩個以上的參數。

感謝advace

+0

所以就是找到具有元數據的有文檔某些鍵/值對(以及所有給定的對必須在那裏)是對的嗎? –

+0

是的:(@Maciej Kowalski – zez

回答

0

作爲鍵 - 值對可在數不同,我會建議與CriteraQuery去爲更多的flexibilty:

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); 
CriteriaQuery<Document> query = criteriaBuilder.createQuery(Document.class); 
Root<Document> root = query.from(Document.class); 
Join<Document, MetaData> metadataJoin = root.join("metaData", JoinType.INNER); 
List<Predicate> predicateList = new LinkedList<Predicate>(); 
//If a map contains all your key value pairs 
for(Map.Entry<String, String> entry : keyValueMap.entrySet()){ 
    predicateList.add(
    criteriaBuilder.and(
     criteriaBuilder.equal(metadataJoin.get("key"), entry.getKey()), 
     criteriaBuilder.equal(metadataJoin.get("value"), entry.getValue()) 
    ) 
); 
} 
query.where(criteriaBuilder.or(
    predicateList.toArray(new Predicate[predicateList.size()])) 
) 
query.groupBy(root.get("idDocument")); 
query.having(criteriaBuilder.equal(criteriaBuilder.count(root.get("idDocument")), predicateList.size())); 
List<Document> documentList = entityManager.createQuery(query).getResultList(); 
+0

什麼是':metadataList'應該包含?JPA將在'IN'語句中執行身份比較,而問題只聲明'鍵/值'對可用作輸入 – crizzis

+0

我的不好。 。編輯一個完整的答案 – grizzly

+0

我從來沒有與CriteriaQuery合作過,明天我會試試它,然後我會在我的電腦旁邊,thx;) – zez