根据Hibernate @GenericGenerator
,只能使用纯JPA,可以在没有的情况下实现以下id生成吗?
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
@Entity
public class MyObject implements Serializable {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "my.IdGenerator")
@Column(name = "ID", length = 36, nullable = false)
private String id;
// ...
}
答案 0 :(得分:1)
您可以使用@PrePersist
回调
@Id
@Column(name = "ID", length = 36, nullable = false)
private String id;
// ...
@PrePersist
public void prePersist() {
id = UUID.randomUUID();
}
有关生命周期回调的更多信息,请访问:Configuring a Life Cycle Callback Method on a JPA Entity
答案 1 :(得分:0)
有一些JPA方法可以实现这一点(意味着它可以通过EclipseLink,Hibernate或其他JPA实现来实现)
如果您有序列对象,请执行以下操作:
@Id
@javax.persistence.SequenceGenerator( name = "mySequence", sequenceName = "MY_TABLE_SEQ", allocationSize = 1, initialValue = 1 )
@javax.persistence.GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "mySequence" )
@Column( name = "MY_TABLE_ID" )
private Integer myTableId;
以下是如果它是一个标识栏:
@Id
@javax.persistence.GeneratedValue( strategy = GenerationType.IDENTITY )
@Column( name = "MY_TABLE_SEQ" )
private Long myTableId;
同样,这里需要注意的是,这是纯粹的JPA,而不是特定于Hibernate的。