Skip to content
Advertisement

Is using id field in @AllArgsConstructor while using Spring JPA correct?

Using spring-boot and JPA I have an Entity I want to use lombok to reduce boilerplate code. However in my entity there is the id field. Shall I put it in the constructor arguments with @AllArgsConstructor or shall I eliminate it from theargument list (somehow, how?) due to being auto-generated with the @id and @GeneratedValue annotations?

code:

JavaScript

Advertisement

Answer

For your question in code:

@AllArgsConstructor // ? is id in constuctor needed?

No it is not needed. Furthermore, for your question in the title:

Is using id field in @AllArgsConstructor while using Spring JPA correct?

Field id it is not recommended to be exposed to any constructor or setter unless there is a very good reason for that. Field id should be manipulated only by JPA implementation.

Note that this expose happens also when you declare @Setter on Reservation class level.

This can be avoided to remove annotation from class level and annotate each field to expose but easier way is to use inheritance.

You can create a base class like:

JavaScript

Note that it does not have setter for field id. Extend above class like:

JavaScript

and the constructors & setters will be the following:

JavaScript

and there is no way – other that reflection that JPA uses – to set the field id.

I do not know how exactly does setting the id but as there is a keyword JPA and tag I assumes this is a JPA thing and that setter for field id is not actually needed at all.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement