Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
Андрей Москвичёв Avatar asked Mar 15 '15 13:03

Андрей Москвичёв


People also ask

How do you get entity based on field value other than ID?

uniqueResult(); This will create a criteria on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue . uniqueResult() tells it to bring a unique result.

What is @ID annotation in JPA?

@Id annotation is the JPA is used for making specific variable primary key.

Can we create JPA entity without ID?

JPA Specifications state that all Entities must have an identifier (JSR 317, section 2.4). It can be a single column or a composite key. You can either put an idAcceso identifier in the Acceso entity or not make Acceso an entity but rather a "component" (which is the purpose of the @Embeddable annotation).

Is @ID mandatory in JPA?

Id is required by JPA, but it is not required that the Id specified in your mapping match the Id in your database. For instance you can map a table with no id to a jpa entity. To do it just specify that the "Jpa Id" is the combination of all columns.


1 Answers

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.

like image 113
JB Nizet Avatar answered Sep 25 '22 23:09

JB Nizet