2015-06-18 72 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