在JPA中是否有一种方法可以在实体实例化后立即检索实体对象的id?例如Person person = new Person();
目前,我在实体类中使用以下策略:@GeneratedValue(strategy = GenerationType.IDENTITY)
如果不是,在数据库中的表设置实际的主键之前,是否有一个“虚拟Id”策略来设置一个dummyId,例如-10等?请注意,MySQL DB中的主键被设置为AutoIncrement。
我需要这样做的原因是能够在列表中添加新的实体,并在将它们保存到DB之前使用JSF数据表中的id对它们进行排序。
发布于 2015-06-18 21:15:13
在持久化之前,无法检索ID --仅仅是因为在持久化实体之前它没有ID。这和你的策略无关。这与赞同有关。
但是,您可以为用例添加自己的临时密钥:
@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;
}
}记住,对于每个创建的对象,即使是那些由JPA提供程序实例化的对象,counter也会减少。如果您只想计算新的(未持久化的)对象,或者担心原子计数器的时间,您应该为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;
}
}发布于 2015-06-18 21:21:39
如果不立即将其保存在DB中,就无法做到这一点,但这显然不是您想要的。如果一次只有一个“新”的人,你可以手动设置“虚拟id”。
person.setId(0L);别忘了在坚持之前把它清除掉。
person.setId(null);
// ...
em.persist(person);https://stackoverflow.com/questions/30921428
复制相似问题