我使用带有H2 DB的spring-boot,我做了一些代码重构。
在我的旧代码库中,我有一个Request实体,它的id跟在DB序列之后。
@Entity
@Table(name = "REQUEST")
public class RequestEntity {
@Id
@Column(name = "ID", length = 256, nullable = false)
@SequenceGenerator(name = "ID_SEQ", sequenceName = "ID_SEQ", allocationSize = 10)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_SEQ")
private Long id;
@Column(name = "REFERENCE", length = 256, nullable = false, unique = true)
private String reference;
}
在我的新代码库中,我将id替换为引用的id作为表的主键。
@Entity
@Table(name = "REQUEST")
public class RequestEntity {
@Id
@Column(name = "REFERENCE", length = 256, nullable = false, unique = true)
private String reference;
}
之前如果我创建了一个实体并存储它,我会得到相同的对象,如下所示:
RequestEntity entity = createRequestEntity() -> RequestEntity@9876
requestRepository.save(entity) -> RequestEntity@9876
requestRepository.findAll() -> [RequestEntity@9876]
但是我得到了新代码:
RequestEntity entity = createRequestEntity() -> RequestEntity@1234
requestRepository.save(entity) -> RequestEntity@4568
requestRepository.findAll() -> [RequestEntity@4568]
正如您所看到的,在第二个示例中,save方法似乎创建了一个新对象并将其保留(RequestEntity @ 4568),这与代码中创建的不同(RequestEntity @ 1234)
有没有人知道行为改变的原因?