I'm new to the JPA arena, and am having problems fetching too much of an entity. I would like to fetch an instance of order, as well as fetching only the ids from the set of OrderItems (Order.items) for example. Currently I can fetch order, and all of the entire Entities of OrderItems. I have tried a loadgraph and a fetchgraph, as well as using a Subgraph without luck.
The Thread @ (Query partial entities with JPA) Provides a possible solution by tagging each attribute with a fetch type, although I'm not sure that would work in my OneToMany case.
Any assistance is greatly appreciated.
I am using a Dynamic entity graph like so: Example slightly modified from (http://www.thoughts-on-java.org/jpa-21-entity-graph-part-2-define/)
EntityGraph<Order> graph = this.em.createEntityGraph(Order.class);
graph.addAttributeNodes("items");
Map<String, Object> hints = new HashMap<String, Object>();
hints.put("javax.persistence.loadgraph", graph);
this.em.find(Order.class, orderId, hints);
An example of the data-structure is as follows:
The Order entity:
@Entity
public class Order implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id = null;
@Version
@Column(name = "version")
private int version = 0;
@Column
private String orderNumber;
@OneToMany(mappedBy = "order")
private Set<OrderItem> items = new HashSet<OrderItem>();
...
The OrderItem entity:
@Entity
public class OrderItem implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id = null;
@Version
@Column(name = "version")
private int version = 0;
@Column
private int quantity;
@ManyToOne
private Order order;
@ManyToOne(fetch = FetchType.LAZY)
private Product product;