【发布时间】: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