【问题标题】:@JoinColumnS involves EAGER fetching in onetoone relation@JoinColumnS 涉及以一对一关系获取 EAGER
【发布时间】:2020-05-28 12:12:15
【问题描述】:

我在两个具有以下结构的类之间有@OneToOne 关系:

用户:

@Getter
@Setter
@NoArgsConstructor
@Entity
public class User implements Serializable {

    @Id
    private Integer id;
    private String login;
    private String password;
    private String name;
    private String address;
    private Boolean active;
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumns( {@JoinColumn(name = "userDetailId", referencedColumnName="id",  insertable=false, updatable=false),
            @JoinColumn(name = "address", referencedColumnName="location", insertable=false, updatable=false)} )
    private UserDetail userDetail;

}

用户详情:

@Getter
@Setter
@NoArgsConstructor
@Entity
public class UserDetail implements Serializable {
    @Id
    private Integer id;
    private String location;

}

在我的 userRepository 中,我使用 entityGraph 来获取 userDetail 查询中的左连接

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
     @EntityGraph(attributePaths = {"userDetail"})
     List<User> findAll();
}

当我调用 findAll() 时,我希望有一个左连接查询,因此休眠使用左连接进行查询,并为用户表中的每一行查询 user_detail,如下所示:

Hibernate: 
    select
        user0_.id as id1_0_0_,
        userdetail1_.id as id1_1_1_,
        user0_.active as active2_0_0_,
        user0_.address as address3_0_0_,
        user0_.login as login4_0_0_,
        user0_.name as name5_0_0_,
        user0_.password as password6_0_0_,
        user0_.user_detail_id as user_det7_0_0_,
        userdetail1_.location as location2_1_1_ 
    from
        user user0_ 
    left outer join
        user_detail userdetail1_ 
            on user0_.user_detail_id=userdetail1_.id 
            and user0_.address=userdetail1_.location
Hibernate: 
    select
        userdetail0_.id as id1_1_0_,
        userdetail0_.location as location2_1_0_ 
    from
        user_detail userdetail0_ 
    where
        userdetail0_.id=? 
        and userdetail0_.location=?

如何禁用对 use_detail 的查询? 我试过了

@Fetch(FetchMode.JOIN)
@LazyToOne(LazyToOneOption.NO_PROXY)

当我使用单个主键 @JoinColumn 而不是 @JoinColumnS 时,休眠只使用左连接进行一个查询,但我需要多个键。 poc的链接here

感谢阅读

【问题讨论】:

    标签: java hibernate jpa jakarta-ee


    【解决方案1】:

    这并不像使用 @OneToMany(默认为 Lazy)或 @ManyToOne 那样简单

    一个可能的解决方案是只使用可能为空的实体进行一对一的引用并按需获取该实体。

    https://stackoverflow.com/a/60108442/10218258 给出了很好的解释。

    【讨论】:

      【解决方案2】:

      我会尝试使用属性optional=false@OneToOne 注释:

      @OneToOne(optional=false)
      

      我过去解决了它,如果我没记错的话,它可能对你的目的是正确的。

      【讨论】:

      • 谢谢你的回答,我只是试试你的提议,我还有两个休眠查询:/
      猜你喜欢
      • 2019-11-03
      • 1970-01-01
      • 2011-12-20
      • 2020-06-29
      • 2016-02-21
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2016-10-02
      相关资源
      最近更新 更多