从String创建实体

时间:2014-07-07 11:01:43

标签: java jpa eclipselink spring-data

我有一个Spring-Data-JPA Role实体,它只包含

+----+------+
| id | name |
+----+------+

其中id和name都是唯一的。

通过使用org.codehaus.jackson.map.ObjectMapper,我尝试将JSON主体映射到包含我的角色实体的实体:

ObjectMapper mapper = new ObjectMapper();
SystemUser systemUser = mapper.readValue(body, SystemUser.class);

我目前最终得到:

Can not instantiate value of type [simple type, class my.backend.domain.Role] from 
JSON String; no single-String constructor/factory method

这意味着,我需要在实体中有一个构造函数:Role(String roleName)。最后,我需要得到结果:

select id, name from role where name=roleName

在构造函数Role(String role name)中?这可能吗?解决这个问题的正确方法是什么?

根据我的要求,我添加了身体信息:

{"userType":"CLIENT","roles": 
["ROLEA","ROLEB"],"companyName":"asdf","address":"asdf","zipCode":"asdf",
"location":"asdf","primaryContact":"asdf","phone":"asdf","fax":"asdf",
"email":"asdf@asdf.com","customerNumber":"asdf","costCenter":"asdf"}

ROLEA和ROLEB也都是Role表中的名称。

1 个答案:

答案 0 :(得分:0)

将存储库注入Role实体,然后使用存储库以工厂方法获取Id

public class Role 
{ 
   @Autowired
   @Transient
   private RoleRepo roleRepo;

   public String id;
   public String name;

   @JsonCreator
   public static Role create(String name) // factory method
   {
      return roleRepo.findRoleByName(name);;
   }
}