java - Spring Data JPA - 如何通过 child ID 获取 parent ?

标签 java spring jpa

我有带有@ManyToMany 注释的父实体和子实体:

@Entity
@Table(name = "parent")
public class Parent {

    @Id
    @GenericGenerator(name = "uuid-gen", strategy = "uuid2")
    @GeneratedValue(generator = "uuid-gen",strategy=GenerationType.IDENTITY)
    private String id;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "parents_childs",
        joinColumns = {@JoinColumn(name = "parent_id", nullable = false, updatable = false)},
        inverseJoinColumns = {@JoinColumn(name = "child_id", nullable = false, updatable = false)})
    private List<Child> childs;
}

和子实体:

@Entity
@Table(name="child")
public class Child {

    @Id
    @GenericGenerator(name = "uuid-gen", strategy = "uuid2")
    @GeneratedValue(generator = "uuid-gen",strategy=GenerationType.IDENTITY)
    private String id;

}

我的任务是找到所有包含具有特定 id 的 Child 的 Parents。我尝试以这种方式在我的存储库中执行此操作:

@Query("select p from Parent p where p.childs.id = :childId and --some other conditions--")
@RestResource(path = "findByChildId")
Page<Visit> findByChild(@Param("childId") final String childId, final Pageable pageable);

异常(exception):

java.lang.IllegalArgumentException: org.hibernate.QueryException: illegal attempt to dereference collection [parent0_.id.childs] with element property reference [id] [select p from Parent p where p.childs.id = :childId and --some other conditions--]

我知道可以解决将 _ 添加到方法名称,如 findByChilds_Id (如 here ),但我找不到如何在 @Query注解。

如何用JPQL来写?

最佳答案

我找到了解决方案:

@Query("select p from Parent p join p.childs c where c.id = : childId and  --some other conditions--")

关于java - Spring Data JPA - 如何通过 child ID 获取 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45554882/

相关文章:

java - 使用 Spring Boot @WebMvcTest 进行测试时如何从我的上下文中排除其他 @Controller

java - 将 SQL 条件添加到 CriteriaQuery

java - 为什么在调用 `pthread_mutex_unlock` 之前调用 `pthread_cond_signal` ?

spring - 尝试连接到MongoLab时URL格式的MongoException

java - cronTrigger 的配置(使用 opensymphony quartz )

java - org.hibernate.MappingException : Repeated column in mapping for entity:. ..column:added_by(应使用 insert ="false"update ="false"进行映射)

java - JPA如何在双向ManyToOne中保留父级

java - 使用 Spring 环境从类路径注入(inject)文件

java - 在 Java 中按字母顺序手动对字符串的 ArrayList 进行排序

java - 并非所有内容类型都支持 Spring REST Controller 内容/类型