有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果属性是实体类型,java如何为其提供值?

我有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表中


共 (3) 个答案

  1. # 1 楼答案

    您需要在数据库中查询正确的AccountType,然后在这里赋值

    当使用JPA时,Java中的所有对象都必须在数据库中有相应的实体。对于JPA映射程序在数据库中找不到字段的对象,无法保存或持久化

    因此,转到您的会话,对您想要的帐户类型运行查询,并分配结果

  2. # 2 楼答案

    您需要编写一个查询来选择要与新帐户关联的AccountType,然后执行以下操作:

    account.setAccountType(objectYouGotFromQuery);
    
  3. # 3 楼答案

    取决于定义枚举/类AccountType的位置。如果AccountType为enum,JPA会自动将enum转换为数据库中的varchar

    public enum AccountType {
       SAVING, CORPORATE, SALARY
    }
    

    然后你可以使用:

    account.setAccountType(AccountType.SAVING);
    //save the account to DB