Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA save "new" Entity with reference to an existing Entity using only it's id?

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.

like image 802
lko Avatar asked Mar 19 '15 19:03

lko


1 Answers

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

like image 93
Master Slave Avatar answered Oct 04 '22 21:10

Master Slave