I try to make JPA Entity's one of the members lazy-fetched in spring boot while using MySQL DB as data source (this might not be mandatory but I'd rather have it mentioned). My entity looks like this:
@Entity
public class DiskFile {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private long id;
@NotEmpty
@Column(unique = true)
private String path;
@Lob
@Column (columnDefinition = "LONGBLOB")
@Basic (fetch = FetchType.LAZY)
private byte[] data;
public DiskFile() {
}
/* Getters and Setters */
}
As you'd guessed I want data
member to be fetched with lazy pattern, because it usually contains megabytes of data. Situation gets even more dire when I try to fetch list of these entities and all of them need to fetch megabytes and megabytes of data.
I know that there are several questions like these on Stackoverflow and I tried solutions mentioned there.
I already know that for hibernate that annotation is only like a recommendation and he might forcefully try to fetch that member Eagerly. So I have added following line to my application.properties
:
spring.jpa.open-in-view = false
And I have already added following plugin into my maven build configurations:
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>${hibernate.version}</version>
<executions>
<execution>
<configuration>
<enableLazyInitialization>true</enableLazyInitialization>
</configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
however I don't get any lazy-fetching with that solutions, since I can see megabytes of data flowing into my system after calling appropriate API endpoint for this entity.
spring.jpa.open-in-view = false
doesn't cause a bunch ofLazyInitializationException
s upon calling the endpoint, but the problem still persists, it means one of two things: (1)FetchType.LAZY
is not respected at all, (2) something is triggering the loading while still within the transaction boundary. To verify (1), set a breakpoint right after the entity is being retrieved and check if theDiskFile.data
is present (it should benull
at that point). (2) is a little tricky, the best course of action would be to enable Hibernate logging to see what queries get executed and when@Basic
properties (e.g.name
)? Maybe the plugin execution does not trigger for some strange reason. If all else fails, you can try the fake one-to-one workaround described here