2014-08-28 22 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 
相关问题