2

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;
Community
  • 1
  • 1
David
  • 21
  • 2
  • What do you mean by only the IDs? A Collection with only the ID field initialized or a Collection containing the IDs? – Alan Hay Apr 14 '16 at 07:49
  • sadly EntityGraph doesn't allow the option of specifying fields NOT to load, just those to specify eager loading on – Neil Stockton Apr 14 '16 at 12:38
  • @AlanHay A Collection with only the ID field initialized was what I ewas thinking, but if I could get a Collection containing the IDs of the OrderItems, that would possibly also work. – David Apr 18 '16 at 15:32

0 Answers0