查询@ElementCollection JPA

Posted

技术标签:

【中文标题】查询@ElementCollection JPA【英文标题】:Query @ElementCollection JPA 【发布时间】:2013-01-21 17:37:46 【问题描述】:

我有一个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

所以,我的数据库Table for transaction_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)

现在,我想用键和值搜索实体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 + "%")));

但是Path&lt;String&gt; propertyKeyPath = propertiesPath.&lt;String&gt; 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]

我通过的参考资料之一是:Spring Data JPA Tutorial Part Four: JPA Criteria Queries,但我没有运气。

【问题讨论】:

【参考方案1】:

解决方案是.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));

更多信息请访问JPA Criteria API - How to add JOIN clause (as general sentence as possible)

【讨论】:

以上是关于查询@ElementCollection JPA的主要内容,如果未能解决你的问题,请参考以下文章

查询中的 JPA 基本类型 ElementCollection 计算值

查询@ElementCollection JPA

LIKE查询HQL实体中Map ElementCollection的值

对 JP-QL (JPA 2.0) 中的“ElementCollection”映射字段执行“MEMBER OF”查询

@ElementCollection 的 JPA 延迟加载

@OneToMany 和 @ElementCollection 之间的区别?