【问题标题】:Fetch a parent by a child in Many-to-Many unidirectional relationship JPA多对多单向关系JPA中的孩子获取父母
【发布时间】:2021-05-18 11:19:48
【问题描述】:

我在 Spring Boot 应用程序中有两个实体 Estate 和 PropertyTags。 Estate 实体与 PropertyTag 具有多对多关系(PropertyTag 也被其他实体使用)

这是庄园实体:

@Entity
public class Estate{
@Id
private Long id;
.
.

@ManyToMany
private Set<PropertyTag> propertyTags;
.
.
// other properties
}

还有 PropertyTag 类:

@Entity
public class PropertyTag{
@Id
private Long id;
private String tagName;

// getters and setters

}

上述关系创建了3个数据库表,其中一个表用于关系的外键。

我需要一个存储库方法(或查询)来检索一个 Estate,该 Estate 将采用一个 Estate Id 和 property 标签对象的参数。

我尝试使用 hibernate 关键字如下:

public interface EstateRepository extends JpaRepository<Estate, Long> {

    Optional<Estate> findByIdAndPropertyTagsContaining(Long estateId, PropertyTag childTag);
   
}

但这没有用。

我不想通过其 ID 检索一个庄园,并手动循环其属性标签以检查其集合中是否存在标签。我觉得这可以通过查询数据库来完成

我不太擅长编写自定义查询。我需要查询方面的帮助才能做到这一点。

谢谢。

【问题讨论】:

    标签: spring-boot jpa


    【解决方案1】:

    要通过PropertyTag 实体获取Estate 实体,您也可以只使用PropertyTag 的id 并尝试

    Optional<Estate> findByIdAndPropertyTags_Id(Long estateId, Long propertyTagId);
    

    应该返回包含具有给定 ID 的标签的 Estate。 Containing 用于字符串搜索

    【讨论】:

    • 谢谢丹尼尔!
    • 不客气。如果该解决方案适合您,请随时将其标记为已接受的答案。 :)
    猜你喜欢
    • 2016-05-13
    • 2018-02-12
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多