springhibernatejpanativequery

Bind left join condition result from query to Entity in Spring Boot Hibernate


I have two tables in database, and when I make query for getting entity of one of the tables, a would like to add one additional field, that is result of condition in left join query, and this field is not in the table. When I make this query in database I getting correct result, but I don't know how to make in 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
);

I would like to add customer_response field in my Entity I tried different ways, but it's not work, this is code in Entity

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

Solution

  • I found answer, I used Hibernate to get this value

    this is query

    @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
    );
    

    and this code in CustomerFormEntity

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

    and this in CustomerResponseEntity

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