2010-01-06 63 views
3

我想添加一個對象到我的客戶端視圖中的集合,並使用hibernate/jpa機制將其保存在服務器上。如何簡單地添加一個對象到客戶端的休眠集合

問題出在這裏: 取一個可以包含Account對象的Group對象。

在我的客戶端視圖(gwt)上,我創建了一個新組(因此id爲空),並向此組添加了一些帳戶(其中存在id)。但這些帳戶初始化在客戶端與他們的ID和僞僅通過一個建議框(因爲我不想在我的客戶端視圖中加載密碼和其他東西)

當我的小組返回到服務器,我嘗試保存它與我的道,我已經得到了這個錯誤: 非空屬性引用null或瞬時值

這是我在組對象關聯:

@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) 
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 
public Set<Account> getAccounts() 
{ 
    return accounts; 
} 

所以堅持必須自動完成。但我認爲問題在於我使用具有現有ID的部分帳戶對象。

我的問題是:如何添加一個簡單的關聯(只需在manyToMany表中添加一條記錄)而不加載所有我想添加的對象(因爲我不需要它,我只是想添加一個關聯兩者之間的ID)

編輯:舉例 更多信息: 我有一組屬性 ID:「G1」 名稱:「1組」

我有哪些屬性的帳戶是 id:「A1」 pseudo:「jerome」 密碼:「pass1」 個狀態:「已啓用」 生日:「XXXX」 ...

從我的客戶端界面(GWT的完成)我加載組1對象 從autcompletion我加載客戶對象,但只有域ID和僞(我不想加載所有的對象)。 我將ID爲「A1」的Account對象「Jerome」添加到我的組中。

我將我的組發送到服務器進行保存。 在服務器我使用的通過調用保存組一個事務性方法: groupDAO.update(MyGroup1的)

如在該組對象我的賬戶對象被部分地加載時,它會導致錯誤。

那麼,如何在不加載整個對象Account的情況下添加我的組和帳戶之間的關聯?我不希望這種代碼:

List newList = new ArrayList(); 
for (Account acc : myGroup1.getAccounts()) 
{ 
    Account accLoaded = accountDAO.findById(acc.getId()); 
    newList.add(accLoaded); 
} 

myGroup1.setAccounts(newList); 
groupDAO.save(myGroup1); 

感謝

回答

4

你的目標:

I just want to add an association between two id without loading the entire object Account

你說:

I think the problem is that i use partial account objects with existing id

你是對的。假設有下面

public class Account { 

    private Integer id; 

    private Integer accountNumber; 

    @Id 
    public Integer getId() { 
     return this.id; 
    } 

    @Column(nullable=false) 
    public Integer getAccountNumber() { 
     return this.accountNumber; 
    } 

} 

所以,當你調用

Group group = new Group(); 

// Notice as shown bellow accountNumber is null 
Account account = new Account(); 
account.setId(1); 

group.addAccount(account); 

entityManager.persist(group); 

因爲CascadeType.PERSIST的所以,你說

Save each referenced Account

但每次提及帳號了accountNumber屬性爲null。這解釋了爲什麼你會得到你的異常

而不是加載完全初始化帳戶您可以使用類似

// If you do not want to hit the database 
// Because you do not need a fully initialized Account 
// Just use getReference method 
Account account = entityManager.getReference(Account.class, new Integer(accountId)); 

所以也沒有什麼意義,你加載每個完全初始化的賬戶沒有任何目的或理由。

關注,

+0

哇!正是我想要的! 非常感謝! – 2010-01-07 08:22:08

+0

+1,完美答案 – whiskeysierra 2010-01-10 19:50:15