在持续存在之前,没有办法检索标识符 - 只是因为它没有标识符,除非您坚持实体。这与你的策略无关。这与同时发生有关。
但是你可以添加自己的临时密钥为您的使用情况:
@Entity
public class Person {
private static final AtomicLong counter = new AtomicLong();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private final transient long tempId = counter.decrementAndGet();
public long getIdForComparison() {
return id == null ? tempId : id;
}
}
记住counter
将减少为每个创建的对象 - 即使是那些由JPA提供商实例化。如果你想只计算新的(非持久)对象,或担心原子计数器的时候,你应该使用不同的构造函数JPA:
@Entity
public class Person {
private static final AtomicLong counter = new AtomicLong();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private transient long tempId;
private String name;
protected Person() {
// Constructor for JPA - nothing to do, the id will get attached
}
public Person(String name) {
// Constructor for creation of new objects
tempId = counter.decrementAndGet();
this.name = name;
}
public long getIdForComparison() {
return id == null ? tempId : id;
}
}
嗨托比亚斯感谢您的回应,我心中有类似的东西,我只是想检查是否有任何东西从jpa implmentations准备! – fruscian