|BatchFetch examples? [message #1758547]
||Thu, 30 March 2017 02:09
| Jason Mesches
Registered: March 2017
We're using JPA and Hibernate and are using a repository pattern. At the repo class, we've defined a query to fetch a list of CustomerOrder entities:|
@Query("SELECT DISTINCT co FROM CustomerOrder co " +
"INNER JOIN co.customerOrderItems coi " +
"WHERE co.customerOrderTypeId IN (1,3,8) " +
"AND co.customerOrderStatusId IN (2,6) " +
"AND co.customerEmail IS NOT NULL " +
"AND coi.performanceId = :performanceId")
List<CustomerOrder> findAllOrdersWithActiveTicketsForPerformance(@Param("performanceId") BigDecimal performanceId);
Because there can be many thousands of these we need to process, and several relationships (some of which are nested), we'd like to avoid the dread n+1 scenario.
If I can get just one of these relationships to work, I'm pretty sure I can do the rest! Here's what we have to link CustomerOrder to CustomerOrderItem.
In CustomerOrderItem (the child entity):
@Table(name = "CUSTOMER_ORDER_ITEM")
public class CustomerOrderItem
@ManyToOne(fetch = FetchType.LAZY)
private CustomerOrder customerOrder;
In CustomerOrder (the parent entity):
@Table(name = "CUSTOMER_ORDER")
public class CustomerOrder
@OneToMany(mappedBy = "customerOrder", fetch = FetchType.EAGER)
private List<CustomerOrderItem> customerOrderItems;
If I leave CustomerOrder.CustomerOrderItems as EAGER I wind up with a bazillion queries, which I would expect if I use EAGER, however I've read answers to questions that swear it must be set to EAGER
If I change to LAZY, I receive a LazyInitializationException. Not sure what I'm doing wrong. Seems like this should be straightforward, but documentation is wrong in some cases, or so sparse that it has one or two lines completely out-of-context and I'm not sure how to apply to our situation.
Anyone have ideas or a snippet of "real world" code I can look at and understand how to make this work?
Powered by FUDForum
. Page generated in 0.02858 seconds