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:

@Entity
@NoArgsConstructor // JPA requires empty constructor
@AllArgsConstructor // ? is id in constuctor needed?

@Getter
@Setter
@ToString(exclude = {"room", "customer"})
public class Reservation {

    @Id
    @GeneratedValue
    private long id;

    private Room room;
    private Customer customer;
    private Date dateFrom;
    private Date dateTo;    
}

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:

@Entity
@Getter
// Choose your inheritance strategy:
//@Inheritance(strategy=InheritanceType.JOINED)
//@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity {
    @Id
    @GeneratedValue
    private Long id;
}

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

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString(exclude = {"room", "customer"})
public class Reservation extends BaseEntity {
    private Room room;
    private Customer customer;
    private Date dateFrom;
    private Date dateTo;    
}

and the constructors & setters will be the following:

Reservation r1 = new Reservation();
Reservation r2 = new Reservation(room, customer, dateFrom, dateTo);

r1.setRoom(room);
r1.setCustomer(customer);
r1.setDateFrom(dateFrom);
r1.setDateTo(dateTo);

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