spring 在Sping Boot Hibernate中将查询的左连接条件结果绑定到实体

fnatzsnv  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(112)

我在数据库中有两个表,当我查询其中一个表的实体时,我想添加一个额外的字段,这是左连接查询中的条件结果,而这个字段不在表中。当我在数据库中查询时,我得到了正确的结果,但我不知道如何在Hibernate中进行。

@Query(
        value = "SELECT c.*, r.id AS customer_response " +
                "FROM postgres.customer_form AS c " +
                "LEFT JOIN postgres.customer_responses AS r " +
                "ON c.id = r.form_id " +
                "AND r.customer_id = :customerId " +
                "WHERE c.id = :formId " +
                "LIMIT 1",
        nativeQuery = true
)
Optional<CustomerFormEntity> findById(
        @Param("formId") int formId,
        @Param("customerId") int customerId
);

我想在我的实体中添加customer_response字段。我尝试了不同的方法,但都无效。这是实体中的代码

@Fetch(FetchMode.JOIN)
@Transient
private Integer customer_response;
von4xj4u

von4xj4u1#

我找到了答案,我用Hibernate得到了这个值
这是查询

@Query(
        value = "SELECT c FROM CustomerFormEntity c " +
                "LEFT JOIN FETCH c.customerResponse res " +
                "WHERE c.id = :formId " +
                "AND ((res IS NULL OR res.customerId = :userId) OR c.userEntity.id = :userId)"
)
Optional<CustomerFormEntity> findById(
        @Param("formId") int formId,
        @Param("userId") int userId
);

CustomerFormEntity中的这段代码

@OneToMany(
        cascade = CascadeType.ALL,
        mappedBy = "form",
        orphanRemoval = true
)
private List<CustomerResponseEntity> customerResponse;

而这在客户响应实体中

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "form_id")
private CustomerFormEntity form;

相关问题