首页 > 解决方案 > 来自其他表 JPA 的映射字段(Spring boot)

问题描述

实体 1

@Data
@Entity
public class Company  implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int companyId;
    private String name;


    @Transient
    private int haveFavoriteUser;

}

实体 2

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @Id
    private String userId;



}

实体 3

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Favorite implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int favoriteId;

    @ManyToOne
    @JoinColumn(name = "userId")
    private User user;

    @ManyToOne
    @JoinColumn(name = "companyId")
    private Company company;
}

存储库:

@Repository
public interface CompanyRepository extends JpaRepository<Company, Long> {

    @Query(value = "SELECT CE.*, IF(F.companyId = CE.companyId, 1, 0) as haveFavoriteUser FROM Company CE " + //
            "LEFT JOIN Favorite F ON CE.companyId = F.companyId " + //
            "WHERE F.userId = :user ORDER BY CE.name", //
            nativeQuery = true)
    List<Company> findAllFavorite(@Param("user") String user);
}

我希望在我的 jpa 存储库映射值“haveFavoriteUser”中,加载来自其他实体(最喜欢的)。我怎样才能做到这一点?

我不想合并公司内部的收藏夹,因为我只需要一个字段。

太感谢了。

标签: javahibernatespring-bootjpa

解决方案


推荐阅读