tags:

views:

282

answers:

2

I have a JPA entity similar to;

public class Inventory {
 private String productname;
 private String manufacturer;
 private Float retailprice;
 private Integer unitssold;
 private String ourcomment;
}

In about 2 out of 5 queries I need the whole entity, but the rest of the time I am not interested in unitssold and ourcomment.

It feels like a waste to make a query and get a large resultlist but only needing 3/5 of the information. I would like to optimize this slightly, and I have a hunch this can be done using inheritence.

But how?

+3  A: 

Inheritance? No.

Even assuming you've had an actual domain entity that consisted of first three fields on your list and Inventory would have extended it, any query you would have made against that entity would inevitably load all fields (via join if mapped to a different table) due to implicit polymorphism.

What you can do is map the 4th and 5th properties as "lazy"; your JPA provider will have to employ bytecode instrumentation in order to be able to do that:

@Basic(fetch = FetchType.LAZY)
private Integer unitssold;

@Basic(fetch = FetchType.LAZY)
private String ourcomment;

You'll have to specify fetch all properties in queries where you need to fetch everything; others will not retrieve property value until first accessed.

To be honest, this approach is only worth it if your queries return large result sets and "lazy" properties are rather big themselves (e.g. I wouldn't do it for Integer alone; String may be feasible if it can get long)

ChssPly76
A: 

Perhaps you could try to map another entity to the same table, marking it as read-only.

Ondra Žižka