【问题标题】:How can I fetch parent entity by child class entity value by JPA query?如何通过 JPA 查询按子类实体值获取父实体?
【发布时间】:2021-06-24 16:13:46
【问题描述】:

我正在尝试通过查询通过子实体获取主要父实体。我的实体如下所示。

主要父实体

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
Public class Buyer{
    
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    List<Account> accounts;
    
}

帐户类

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Account{
}

Account 类在下面的类中继承

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
@DiscriminatorValue("buyer1")
public class BuyerAccount1 extends Account {
    @Column(unique = true)
    private UUID buyerId;

}

我想通过resourceId 现有BuyerAccount1 获得Optional。我已经尝试了下面的 JPA 查询来做到这一点,但我得到了 Optional.empty() 作为响应。

@Query("SELECT pb \n" +
            " FROM Buyer pb join pb.accounts a \n" +
            " WHERE  a.buyerId= :buyerId \n" +
            " AND type(a) = BuyerAccount1")
    Optional<Buyer> findByBuyerAccount1(@Param("buyerId") UUID buyerId);

我是否在查询中遗漏了什么?

提前致谢!!

【问题讨论】:

    标签: java spring-boot hibernate jpa hibernate-query


    【解决方案1】:

    我建议你改用这样的查询:

    @Query("SELECT pb \n" +
            " FROM Buyer pb \n" +
            " WHERE EXISTS (SELECT 1 FROM pb.accounts a WHERE a.buyerId = :buyerId)")
    Optional<Buyer> findByBuyerAccount1(@Param("buyerId") UUID buyerId);
    

    除此之外,如果你使用 MySQL,你需要为 UUID 类型指定一个长度,因为它默认生成为binary(255),这将导致填充值。使用@Column(length = 16)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2017-05-23
      相关资源
      最近更新 更多