查询@ElementCollection JPA

pra*_*upd 5 java spring hibernate jpa hibernate-criteria

我有一个Entity Transaction如下:

@Entity
class Transaction extends AbstractEntity<Long>{
        private static final long serialVersionUID = 7222139865127600245L;
        //other attributes

    @ElementCollection(fetch = FetchType.EAGER, targetClass = java.lang.String.class)
    @CollectionTable(name = "transaction_properties", joinColumns = @JoinColumn(name = "p_id"))
    @MapKeyColumn(name = "propertyKey")
    @Column(name = "propertyValue")
    private Map<String, String> properties;

    //getters and setters
}
Run Code Online (Sandbox Code Playgroud)

所以,我的数据库Tabletransaction_properties

mysql> desc transaction_properties;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| p_id          | bigint(20)   | NO   | PRI |         |       |
| propertyValue | varchar(255) | YES  |     | NULL    |       |
| propertyKey   | varchar(255) | NO   | PRI |         |       |
+---------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

现在,我想Transaction用键和值搜索实体.

    Path<Map<String, String>> propertiesPath = root.get("properties");
    Path<String> propertyKeyPath = propertiesPath.<String> get("propertyKey"); //where m getting error
    Path<String> propertyValuePath = propertyKeyPath.<String> get("propertyValue");
    p = cb.and(p, cb.and(cb.like(propertyKeyPath, "%" + searchTrxnKey + "%"), cb.like(propertyValuePath, "%" + searchTrxnValue + "%")));
Run Code Online (Sandbox Code Playgroud)

但我得到的错误Path<String> propertyKeyPath = propertiesPath.<String> get("propertyKey");如下:

[...] threw an unexpected exception: org.springframework.dao.InvalidDataAccessApiUsageException: Illegal attempt to dereference path source [null]; nested exception is java.lang.IllegalArgumentException: Illegal attempt to dereference path source [null]
Run Code Online (Sandbox Code Playgroud)

我经历的一个参考是:Spring Data JPA教程第四部分:JPA Criteria Queries但对我来说没有运气.

pra*_*upd 11

该解决方案是.join("properties")不是.get("properties").

Path<Map<String, String>> propertiesPath = root.join("properties");
predicate = (predicate != null) ? criteriaBuilder.and(predicate, criteriaBuilder.and(propertiesPath.in(searchTrxnKey), propertiesPath.in(searchTrxnValue)))
                                : criteriaBuilder.and(propertiesPath.in(searchTrxnKey), propertiesPath.in(searchTrxnValue));
Run Code Online (Sandbox Code Playgroud)

更多JPA Criteria API - 如何添加JOIN子句(尽可能作为一般句子)