使用Spring JPA时在@AllArgsConstructor中使用id字段正确吗?

mCs*_*mCs 3 spring jpa lombok spring-data-jpa spring-boot

使用spring-boot和JPA我有一个Entity我想使用lombok来减少样板代码。但是在我的实体里有这个id领域。我应该将它放在带有构造函数的参数中,@AllArgsConstructor还是应该将其从参数列表中删除(以某种方式,如何?),因为它是使用@id@GeneratedValue注释自动生成的?

码:

@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;    
}
Run Code Online (Sandbox Code Playgroud)

pir*_*rho 5

对于代码中的问题:

@AllArgsConstructor //吗?是否需要构造器中的id?

不,不需要。此外,对于标题中的问题:

使用Spring JPA时在@AllArgsConstructor中使用id字段正确吗?

现场id不建议暴露于任何构造函数或setter,除非有非常充分的理由。id只能由JPA实现来操纵字段。

请注意,当您@SetterReservation类级别上声明时,也会发生这种暴露。

可以避免从类级别删除注释并注释每个字段以使其公开,但是更简单的方法是使用继承。

您可以创建一个类似的基类:

@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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,它没有设置field的设置器id。像上面这样扩展类:

@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;    
}
Run Code Online (Sandbox Code Playgroud)

构造器和设置器将如下所示:

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

r1.setRoom(room);
r1.setCustomer(customer);
r1.setDateFrom(dateFrom);
r1.setDateTo(dateTo);
Run Code Online (Sandbox Code Playgroud)

而且,除了JPA使用的其他反射方式之外,没有其他方法可以设置该字段id

我不知道是如何准确设置的,id但是由于有一个关键字JPA和标签我认为这是一个JPA事情,并且id实际上根本不需要字段设置方法。