2015-06-18 73 views
0

在JPA实体实例化后,是否有办法在JPA中检索实体对象的ID?例如Person person = new Person();实体实例化后立即检索实体对象的ID?

目前,我用我的实体类以下策略: @GeneratedValue(strategy = GenerationType.IDENTITY)

如果不是有一个“虚拟ID”的策略对于具有dummyId例如-10等之前的实际主键被设置数据库中的表?请注意,MySQL DB中的主键被设置为AutoIncrement。

我需要这个的原因是能够在列表中添加新实体,并在将它们保存到数据库之前使用JSF数据表中的id对它们进行排序。

回答

0

在持续存在之前,没有办法检索标识符 - 只是因为它没有标识符,除非您坚持实体。这与你的策略无关。这与同时发生有关。

但是你可以添加自己的临时密钥为您的使用情况:

@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; 
    } 

} 
+0

嗨托比亚斯感谢您的回应,我心中有类似的东西,我只是想检查是否有任何东西从jpa implmentations准备! – fruscian

0

有没有办法不用在DB的权利将它保持离开,但这显然不是你想要的,毕竟。假设一次只有一个“新人”,您可以手动设置“虚拟身份证”。

person.setId(0L); 

不要忘记清除它之前坚持。

person.setId(null); 
// ... 
em.persist(person); 
+0

如果使用基于字段的访问(更常见的情况),那么我会建议不为ID创建setter,因为'getId()!= null'将是一个便宜的指示器,表明实体是持久的。我认为ID应该是不可改变的。 –

+0

从这个角度来看,你是完全正确的。 – BalusC