Tyler Durden Tyler Durden -3 years ago 83
Java Question

Can you use lambda expressions in a JPA Entity with good performance?

So, I have a OneToMany relationship in one of my entites:

@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REFRESH }, fetch = FetchType.LAZY)
private List<Result> results

I want to get objects contained inside of these "results" based on by some criteria:

Stream<Item> itemsToReturn = results.stream().filter(result -> result.getPriority() > 5)
.filter(/*some filtering logic*/)

It doesn't seem to be very effective though, since I guess all Items will be loaded into memory before any filtering is done in spite of the filtering and the limit.

Is my assumption correct? If so, can I do something so that I can use lambda in this entity, or I should write a JPA query to get these items?

Can lambdas be used with JPA at all?

Answer Source

Whether it is good or not depends on how big your result set is. But it is worth knowing whats gonna happen when you execute your code.

  1. A full scan will execute on the db table
  2. The entire table data will be traveling over the network wire
  3. The entire result set will be loaded into the JVM main memory
  4. A linear scan will execute over the entire result when you do the filer over the stream

The above code is not any different from an old fashion for-loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download