2017-02-17 14 views
0

這是一個問題,我問EJB/JPA:堅持一個實體對象後,它的getId()返回0 - 即使它被正確地存儲在表

編輯的簡化,並希望更清晰的版本:我「M在NetBeans工作,持久性提供是進入休眠模式,在此是實際的數據庫表的圖像(響應於@xiumeteo):

enter image description here

基本上,我的問題是,我的自動生成的ID值時我堅持一個實體,即使實體正確地保存到數據庫中,正確的ID> 0,entityMa nager似乎總是認爲現在持久化的實體的ID爲0.這導致後續違反外鍵約束,但在這裏我只關注Id是(或者更確切地說)0,因爲這應該是與問題的原因密切相關,實際上它本身就是一個謎。

所以我有一個簡單的實體類人:

@Entity 
    public class Person { 

     @Id 
     @GeneratedValue(strategy = GenerationType.IDENTITY) 
     @Column(nullable = false, unique = true) 
     private Long id; // I’ve also tried types Integer and int, doesn’t make a difference. 

     @Column(nullable = false) 
     private String name; 

     @Column(nullable = false) 
     private String email; 
     public Person() { 
     } 

     public Long getId() { 
      return id; 
     } 

     public void setId(Long id) { 
      this.id = id; 
     } 

    // setters and getters for the other fields omitted here. 
    } 

然後,我有一個會話bean,包含一方法創建(P),其堅持的人,對象號碼:

@Stateless 
    @Default 
    public class PersonRepositoryImpl implements PersonRepository { 

     @PersistenceContext 
     private EntityManager entityManager; 

    @Override 
    @Transactional // Deleting this annotation makes no difference, only added 
         it because I thought it might solve the problem... 
    public Person create(Person p) { 
     entityManager.persist(p); 
     entityManager.flush(); // Again, only added this statement because I thought it 
            might solve the issue, which it did not. 
     return p; 
     } 
    } 

現在本身,create(p)方法執行它應該做的事情:它將人員p保存到PERSON-table中,並具有正確生成的ID。

然而,當我嘗試人對象已經堅持之後獲得該ID的價值問題變得明顯;它仍然是0.因此,我從servlet調用create(p)方法,然後立即獲取持久化對象的ID並將其打印到控制檯,如下所示(注意:personRepo是會話bean的注入實例其定義上面找到):

Person p = new Person(); 
p.setName("Carl"); p.setEmail([email protected]); 
p = personRepo.create(p); // Everything going fine here => entity p gets stored 
          in the PERSON table with a correctly generated ID>0.  
System.out.println("The newly persisted entity now has the following ID: " + p.getId()); 

這最後的println語句始終打印0作爲p.getId()的值,而我希望它打印對應錶行的ID值該實體。

在類似的問題的答案中,我讀過調用flush()應該有所幫助(這就是爲什麼我將它添加到上面的create-method),但顯然在我的情況下它不。如上所述,即使從create()方法(實際持久化)返回到調用servlet後,Id字段仍然被賦予值爲0.儘管如我所說,它是在存儲在具有正確ID> 0的數據庫表PERSON中的點。

那麼如何讓getId()函數返回REAL ID? (並且通過擴展,希望獲得entityManager/container以'看''真實的id值,以便實體可以參與多對多關係而不違反FK約束。)

+0

哪個db在這個例子中使用? – xiumeteo

+0

持久性提供者是Hibernate。真正的數據庫是JavaDB/Derby(請參閱問題本身中新附加的圖像。 – Holland

+0

這是對@xiumeteo的迴應... – Holland

回答

-2

嘗試使用session.save(p)而不是entityManager.persist(p)save()將返回一個標識符,並且如果必須執行INSERT以獲取標識符,則此INSERT立即發生。

OR

嘗試刷新實體沖洗後,重新讀取該實體的狀態。

entityManager.persist(p); 
entityManager.flush(); 
entityManager.refresh(p); 
+0

JPA API中沒有'entityManager.save(p)'! –

+0

雖然那是'session.save()'大聲笑 – Angga

+0

好吧,我錯了之前:(編輯.. – Angga

相關問題