48 lines
1.5 KiB
Plaintext
48 lines
1.5 KiB
Plaintext
![]() |
`FetchType` is an enumeration in the Java Persistence API (JPA) that is used to define the fetching strategy for associations (relationships) between entities in a relational database.
|
||
|
|
||
|
There are two main values for FetchType:
|
||
|
|
||
|
- `FetchType.EAGER`: the association is loaded immediately when the owning entity is loaded.
|
||
|
- `FetchType.LAZY`: the association is not loaded unless it is explicitly accessed.
|
||
|
|
||
|
This rule raises an issue when the `fetch` argument is explicitly set to `FetchType.EAGER`.
|
||
|
|
||
|
== Why is this an issue?
|
||
|
|
||
|
Using `FetchType.EAGER` can lead to inefficient data loading and potential performance issues.
|
||
|
Eager Loading initializes associated data on the spot, potentially fetching more data than needed.
|
||
|
|
||
|
== How to fix it
|
||
|
|
||
|
Remove or replace `FetchType.EAGER` with `FetchType.LAZY` in JPA annotations.
|
||
|
|
||
|
=== Code examples
|
||
|
|
||
|
==== Noncompliant code example
|
||
|
|
||
|
[source,java,diff-id=1,diff-type=noncompliant]
|
||
|
----
|
||
|
@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER) // Noncompliant
|
||
|
private List<ChildEntity> children;
|
||
|
|
||
|
@OneToMany(mappedBy = "child", fetch = FetchType.EAGER) // Noncompliant
|
||
|
private List<ParentEntity> parents;
|
||
|
----
|
||
|
|
||
|
==== Compliant solution
|
||
|
|
||
|
[source,java,diff-id=1,diff-type=compliant]
|
||
|
----
|
||
|
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) // Compliant
|
||
|
private List<ChildEntity> children;
|
||
|
|
||
|
@OneToMany(mappedBy = "child") // Compliant
|
||
|
private List<ParentEntity> parents;
|
||
|
----
|
||
|
|
||
|
== Resources
|
||
|
|
||
|
=== Documentation
|
||
|
|
||
|
* https://docs.oracle.com/javaee/7/api/javax/persistence/FetchType.html[Java EE 7 API - FetchType]
|