java - JPA 2——在 CriteriaQuery 中使用@ElementCollection

标签 java orm jpa jpa-2.0 criteria-api

    @Entity
    public class Person {

        @ElementCollection
        private List<Location> locations;

        [...]

    }

    @Embeddable
    public class Location {

        private Integer dummy;

        private Date creationDate;

        [...]

    }

给定以下结构,我想执行与以下 SQL 等效的 HQL 或 CriteriaQuery:

SELECT
    l.*
FROM
    Location l
INNER JOIN
    Person p ON (p.id = l.person_id)
WHERE
    p.id = ? AND l.creationDate > ?

我想取回与给定人员关联且其创建日期晚于给定人员的位置列表。

提前致谢!

标记

编辑***:我已经编辑了 SQL,因为它有点误导。我不想独立查询位置。

最佳答案

这是不可能的,您不能查询 Embeddable。来自 JPA 维基教科书:

Embedded Collections

An ElementCollection mapping can be used to define a collection of Embeddable objects. This is not a typical usage of Embeddable objects as the objects are not embedded in the source object's table, but stored in a separate collection table. This is similar to a OneToMany, except the target object is an Embeddable instead of an Entity. This allows collections of simple objects to be easily defined, without requiring the simple objects to define an Id or ManyToOne inverse mapping. ElementCollection can also override the mappings, or table for their collection, so you can have multiple entities reference the same Embeddable class, but have each store their dependent objects in a separate table.

The limitations of using an ElementCollection instead of a OneToMany is that the target objects cannot be queried, persisted, merged independently of their parent object. They are strictly privately-owned (dependent) objects, the same as an Embedded mapping. There is no cascade option on an ElementCollection, the target objects are always persisted, merged, removed with their parent. ElementCollection still can use a fetch type and defaults to LAZY the same as other collection mappings.

要实现您想要的效果,请使用 OneToManyEntity 而不是 ElementCollectionEmbeddable .或者改变您的方法并查询 Person

关于java - JPA 2——在 CriteriaQuery 中使用@ElementCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3708914/

相关文章:

java - graphql-spring-boot 上传二进制文件

java - 内部存储:微调器值和 TextView 为整数

java - Hibernate - 使用mappedBy时外键为空

java - Hibernate能否映射a的结果集 1 :M join in a subselect to a parent with a child collection?

java - Hibernate 继承 JOINED + TABLE PER CLASS

mysql - 在 Hibernate 中闲置 5 分钟后无法连接到数据库

java - Java : Unexpected Type Error [duplicate]

java - 如何禁用 Spring Boot Hibernate "Listing entities"选项?

php - 在 Laravel 5 中批量插入

SQL Server 的 Java O/R 层?