I am looking for performance improvements in certain aspects of my application and wondered if its possible to insert a new entity that holds a reference to to a Many-To-One object without having to fully load the Many-To-One object in advance.
For example,
Code:
@Entity
CustomerInvoice
{
//Lots of properties
}
@Entity
PaymentAllocation
{
@Id @GeneratedValue
private Long id;
@ManyToOne(fetch=FetchType.LAZY)
private CustomerInvoice customerInvoice;
private BigDecimal allocateAmount;
}
My scenario is I have a batch process to process payments. My method will take a List<Long> of customerInvoice id's from a remote application. So I *know* the id of the CustomerInvoice.
This code will work fine:
Quote:
//Load up customer invoice
CustomerInvoice invoice = em.find(CustomerInvoice.class, id);
//Create new allocation
PaymentAllocation allocation = new PaymentAllocation();
allocation.setCustomerInvoice(invoice);
allocation.setAllocateAmount(allocate);
em.create(allocation):
The problem with above is that having to find the customer invoice generates a lot of SQL with all the properties and related objects on the CustomerInvoice entity. This is to be as expected. The thing is, I don't actually need to reference the customer invoice or any of these properties *in this instance*. I only need the CustomerInvoice object to reference on the payment allocation.
I'd like to be able to do something like this:
Quote:
//Load up customer invoice
CustomerInvoice invoice = new CustomerInvoice();
invoice.setID(213);
//Create new allocation
PaymentAllocation allocation = new PaymentAllocation();
allocation.setCustomerInvoice(invoice);
allocation.setAllocateAmount(allocate);
em.create(allocation):
So the difference being I am not loading the CustomerInvoice obj, but simply setting the id which I hope would then give the allocation code the id to reference. Doing this however will cause a hibernate exception "object references an unsaved transient instance before flushing". Is there a way to overcome this or am I stuck with having to load up the invoices?
Thanks for any suggestions!