Store JPA entity with given field object id instead of object itself

The problem is following:

We have entity:

@Entity
public class Feedback {
    @Id
    @GeneratedValue(generator="token")
    private String id; 

    @ManyToOne
    private Product product;

    private String message;

    // other fields
}

And we have a server endpoint, that receives feedback from clients. Feedback received in multipart/form-based format, with fields:

 ProductId - product identifier
 Message - feedback message
 Some other fields

To set Feedback.product we need to load Product object from JPA - this can be time-consuming and it creates unnecessary queries.

Is it possible to store entity, but pass the product id instead of the product object? We need some way to modify the INSERT query.

We use EclipseLink JPA with Spring and Vaadin.

Upvotes: 6

Views: 2707

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

Use EntityManager.getReference(): if the entity is not loaded already, it simply creates a lazy-initialized proxy around the ID, without causing any SQL query to be executed.

Upvotes: 8

Related Questions