问题
现在有2个实体:Author、Contact,关系是一对一,Contact表负责维护关联关系,如图:

实体定义如下:
- Author
java
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "author")
private Contact contact;
}
- Contact
java
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String mobile;
private String email;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn( name = "author_id",referencedColumnName = "id")
private Author author;
}
现在有一个需求,要根据authorId查询author,但是不需要把author关联的contact也查出来,虽然我们这里配置了延迟加载contact,但是实际查询的时候,还是把contact查出来了,如下:
java
@Transactional(readOnly = true)
public AuthorVO getById(Long id) {
return authorRepository.findById(id)
.map(author -> new AuthorVO(author.getId(), author.getName()))
.orElse(null);
}
SQL日志:
java
Hibernate: select a1_0.id,a1_0.name from author a1_0 where a1_0.id=?
Hibernate: select c1_0.id,c1_0.author_id,c1_0.email,c1_0.mobile from contact c1_0 where c1_0.author_id=?