Reputation: 158
There is this JPA Entity (let's call it Foo
) that I use to display on the FrontEnd. The Entity is linked to another entity by a join (Let's call it Bar
).
So the backstory here is that I don't need Bar
in the FrontEnd call (When calling the Foo
Entity/ties), I only need it for a BackEnd call (When calling the Foo
Entity/ties). Is there a way to conditionally exclude the joined Bar entity when calling Foo
entities via the JPA FooRepository
?
PS: Let's say one Foo
entity is linked to a 1000 Bar
entities and I don't want it to delay displaying in the FrontEnd because of entities that are not going to be useful in the FrontEnd.
The below is the JPA Entity for Foo
public class Foo implements Serializable {
@Id
@Column(name = "id")
private BigInteger id;
@Column(name = "name")
private String name;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumns({
@JoinColumn(name = "id" , referencedColumnName = "foo_id")
})
private List<Bar> barList;
}
And this is the JPA Entity for Bar
public class Bar implements Serializable {
@Id
@Column(name = "key")
private BigInteger key;
@Column(name = "foo_id")
private BigInteger fooId;
@Column(name = "back_code")
private String backCode;
@Column(name = "date_cap")
private Date dateCap;
@Column(name = "hash")
private String hash;
}
Below is the JPA Repository for Foo, with no custom methods, I am only using findAll()
and findById()
public interface FooRepository extends JpaRepository<Foo, BigInteger>{
}
Upvotes: 2
Views: 1241
Reputation: 7596
Mark barList with FetchType.Lazy
@OneToMany(fetch=FetchType.LAZY, ...)
That will make it not load the barList by default. In the method where you want to load barList you access the list somehow, for instance with calling its size()
@Transactional
public Foo getFullyPopulatedFoo(BigInteger key) {
var foo = fooRepo.findById(key)
foo.getBarList().size(); // may cause error if foo was not found
return foo;
}
or by having a separate method to return its barList. Notice that loading the barList need to be done within the same transaction as fetching Foo, for instance in a service method.
@Transactional
public List<Bar> getBarsFromFoo(BigInteger key) {
return fooRepo.findById(key).getBarList(); // may cause error if not found
}
What to consider is if it would be better to remap Foo / Bar to some sort of DTO before leaving the service/transaction layer since if you return Foo without populating barList, then you return an incomplete entity that may or may not have entries in the database but not in the entity you have returned.
Upvotes: 1