我在两个类之间有 @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() 时,我希望有一个左连接查询,因此 Hibernate 会使用左连接进行查询,并针对用户表中的每一行对 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 时,hibernate 仅使用左连接进行一个查询,就像我一样,但我需要多个键。 poc的链接here
感谢您阅读我的文章
最佳答案
这并不像使用@OneToMany(默认情况下是Lazy)或@ManyToOne那样容易
一个可能的解决方案是仅拥有可能为空的一对一引用的实体,并按需获取该实体。
关于java - @JoinColumnS 涉及一对一关系中的 EAGER 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60196770/