11

Say you have a Car with a collection of Tires.

@Entity
public class Car {
    private Long id;
    @OneToMany(mappedBy = "car")
    private Set<Tire> tires = new HashSet<>();
}

@Entity
public class Tire {
    private Long id;
    ...
}

Now if you want to add a new Car and add existing Tires you could go fetch the entire existing Tire Entities to populate the Car's Set.

Is is possible to simply have some Tire IDs and save the Car without fetching the entire Tire entity(ies) into memory first? Is there a way to save it with just a Tire Id if it were just a Single Tire instance instead of a Set? Using JPA and the Criteria API, or maybe JPQL.

lko
  • 7,631
  • 9
  • 37
  • 57
  • 1
    Nope. The whole point of JPA is to represent and handle the relationships, so you cannot hack by using the knowledge how the relatinships are actually implemented in your db layer. – Zielu Mar 19 '15 at 19:15
  • You can use Entity Graphs to fetch partially populated objects. – Zielu Mar 19 '15 at 19:20
  • What version of JPA are you using? I have tested here with JPA 2.1 and it is not loading all the collection just to add an item to the list. – uaiHebert Mar 19 '15 at 20:26

1 Answers1

13

You can use an id to load a proxy "deputy" object, via EntityManager.getReference. It will not issue any DB queries unless you access any property of the object.

If you do access a property, a lazy-loading mechanism will kick-in and load an actual object. The following question demoed the anatomy of the proxy object. Usefull for getting a better picture

Kariem
  • 3,366
  • 2
  • 38
  • 57
Master Slave
  • 24,735
  • 4
  • 53
  • 54