【发布时间】:2017-06-18 19:08:48
【问题描述】:
在我的 java spring 应用程序中,我正在使用 hibernate 和 jpa,并且我使用 jackson 在 DB 中填充数据。
这是用户类:
@Data
@Entity
public class User{
@Id
@GeneratedValue
Long id;
String username;
String password;
boolean activated;
public User(){}
}
第二类是:
@Entity
@Data
public class Roles {
@Id
@GeneratedValue
Long id;
@OneToOne
User user;
String role;
public Roles(){}
}
在 Roles 类中,我有一个 User 属性 然后我制作了一个 json 文件来存储数据:
[ {"_class" : "com.example.domains.User", "id": 1, "username": "Admin", "password": "123Admin123","activated":true}
,
{"_class" : "com.example.domains.Roles", "id": 1,"user":1, "role": "Admin"}]
不幸的是,当我运行它抱怨的应用程序时:
.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.example.domains.User: no int/Int-argument constructor/factory method to deserialize from Number value (1)
at [Source: N/A; line: -1, column: -1] (through reference chain: com.example.domains.Roles["user"])
问题出在
{"_class" : "com.example.domains.Roles", "id": 1,"user":1, "role": "Admin"}
当我删除上述行时,应用程序运行良好。
我认为,它抱怨是因为它无法创建用户实例。 那么,我该如何解决?
【问题讨论】:
-
它直接说明了问题所在:它无法将整数 1 映射到具有“用户”类型的字段上。您应该在输入中使用用户对象而不是外键引用。或者做我喜欢的事情,编写一个包含您真正感兴趣的字段的 DTO,然后应用您需要的任何业务逻辑来使实体正常工作。
-
我没听明白。你能写一个答案吗?
-
从业务角度来看,一对一是否正确?
-
我猜,问题出在您设置“id”的值,而它应该是自动生成的。
标签: java spring hibernate jpa jackson