问题
I have two entity classes as below and corresponding repository interface
Entity 1
@Data
@NoArgsConstructor
@Entity
@Table(name = "person_details")
public class PersonDetails {
@Id
private String pid;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "exist_flag")
private String existFlag;
@OneToOne(mappedBy = "personDetails", cascade = CascadeType.ALL)
private AddressDetails addressDetails;
}
Entity 2
@Data
@NoArgsConstructor
@Entity
@Table(name = "address_details")
public class AddressDetails {
@Id
private String pid;
private String street;
@Column(name = "address_exist_flag")
private String addressExistFlag;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "pid", insertable = false, updatable = false)
private PersonDetails personDetails;
}
Corresponding repository interfaces
public interface PersonDetailsRepository extends JpaRepository<PersonDetails, String> {
}
public interface AddressDetailsRepository extends JpaRepository<AddressDetails, String> {
}
If i call findAll on PersonDetailsRepository instance, I should get details of both PersonDetails and AddressDetails which I am getting with current implementation.
If i call findAll on AddressDetailsRepository instance, I should get details of only AddressDetails which I am not getting with current implementation. How can I achieve this without impacting findAll on PersonDetailsRepository instance?
回答1:
By default only one to many relation is lazily loaded in hibernate. Even if we instruct hibernate to lazily load, hibernate disregards that hint. To overcome this problem, we need to enable bytecode enhancement.
Bytecode Enhancement
Bytecode enhancement plugin that enhances the bytecode of entity classes and allows us to utilize No-proxy lazy fetching strategy.We can define the plugin in pom.xml file in the following way
<build>
<plugins>
<plugin>
<groupId>org.hibernate.orm.tooling</groupId
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>5.4.2.Final</version>
<executions>
<execution>
<configuration> <enableLazyInitialization>true</enableLazyInitialization> </configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Enabling no proxy lazy associations
Now we need to add @LazyToOne
annotation in entity classes to let hibernate know that we want to enable no proxy lazy fetching for associated entities.
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@LazyToOne(LazyToOneOption.NO_PROXY)
@JoinColumn(name = "pid", insertable = false, updatable = false)
private PersonDetails personDetails;
来源:https://stackoverflow.com/questions/60929734/spring-data-jpa-findall-can-be-called-on-associated-entity-of-onetoone-mapping