Jackson:将对象作为属性引用
在我的java spring应用程序中,我正在使用hibernate和jpa,我使用jackson在DB中填充数据。
下面是 User 类:
@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(){}
}
在类角色中,我有一个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"}
当我删除上面的行时,应用程序运行良好。
我认为,它抱怨是因为它不能成为用户的实例。那么,我该如何解决它?