2014-08-28 16 views
0

我有PERSON,ACCOUNT,PERSON_ACCOUNT(用於Person和Account的多對多關係)表和實體。 現在Account類型保存,企業,工資.. 這種類型是ACCOUNT_TYPE表中的預定義值(創建表)。如何爲屬性提供值如果它是實體的類型?

我有很好的定義關係。爲Account類 小碼

class Account{ 
private AccountType acctype; 
} 

現在我想創建

     Person p = new Person(); 
         p.setFirstName(); 
         p.setLastName(); 

         Account account=new Account(); 
         account.setAccountType() ? // how I get predefine value from database to here? 

        Set accounts; // other code to create set 
        p.setAccounts(accounts); 

我的問題是我怎麼寫account.setAccountType(accountTypeEntity.getAccountType())
它不應該插入數據到ACCOUNT_TYPE表。

回答

2

您需要在數據庫中查詢正確的AccountType,然後在此處指定值。

使用JPA時,Java中的所有對象都必須在數據庫中具有相應的實體。您無法保存或保留具有JPA映射器在數據庫中找不到的字段的對象。

因此,請轉到您的會話並針對您想要的帳戶類型運行查詢並分配結果。

+0

先生的數據是已經存在像(儲蓄,企業,工資)..但我如何給價值account.setAccountType(上面一個?) – user3543851 2014-08-28 09:32:15

+0

展我可以使用代碼從會話管理器加載帳戶類型「保存」。 – 2014-08-28 09:33:04

0

你需要編寫一個查詢來選擇要關聯到新帳戶ACCOUNTTYPE,然後做

account.setAccountType(objectYouGotFromQuery); 
0

要看,枚舉/類ACCOUNTTYPE定義在哪裏。如果AccountType是枚舉,則JPA會自動將枚舉轉換爲數據庫中的varchar。

public enum AccountType { 
    SAVING, CORPORATE, SALARY 
} 

那麼你可以使用:

account.setAccountType(AccountType.SAVING); 
//save the account to DB 
相關問題