我正在从事一个 Spring Boot 项目,需要将 JSON 转换为实体以保存在 postgresql 数据库中。我有一些自引用关系,不知道如何反序列化并保存在数据库中。我有一个与其他用户有某种关系的用户。例如,用户 A 是用户 B 的客户。
让我们看示例代码以更好地理解...
我有以下 JSON 将信息保存到数据库中
{
id: 1,
name: "myName"
relations:[
{
"user_id": "2",
"relation": "relation_name"
},
{
"user_id": "3",
"relation": "other_relation_name"
}
]
}
我有以下课程(示例代码)
@Entity
@Data
public class User {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "user_id_parent")
private List<UserRelation> relations;
}
@Entity
@Data
public class UserRelation {
@Id
@ManyToOne(targetEntity = User.class)
@JoinColumn(name = "user_id_parent", referencedColumnName = "id", nullable = false)
private Long user_id_parent;
@Id
@JsonProperty("user_id")
private Long user_id_child;
private String relation;
}
为了反序列化并保存在数据库中,我这样做
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json.toString(), User.class);
// user have [User(id=1, name:"myName", relations=[UserRelation(user_id_child=2, relation="relation_name", user_id_parent=null)]]
userRepository.save(user);
但是,我有这个错误:
Unable to find com.compani.project.domain.UserRelation with id UserRelation(user_id_child=2, relation=null, user_id_parent=null)
我不知道如何做好这项任务。有什么想法或建议吗?
编辑 @Wladimir Diskowski建议在User实体中定义Cascade Persist,我这样写
@Entity
@Data
public class User {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "user_id_parent", cascade = { CascadeType.PERSIST })
private List<UserRelation> relations;
}
但是我有这个错误
not-null property references a null or transient value : com.compani.project.domain.UserRelation.user_id_parent
我认为问题在于,为什么要在
user_id_parent
中设置paren用户的ID(在本例中为值1)
我的意思是:
@Entity
@Data
public class User {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "userParent", cascade = { CascadeType.PERSIST })
private List<UserRelation> relations;
}
@Entity
@Data
public class UserRelation {
@Id
@ManyToOne(targetEntity = User.class)
@JoinColumn(name = "user_id_parent", referencedColumnName = "id", nullable = false)
@JsonIgnore
private User userParent;
@Id
@JsonProperty("user_id")
private Long user_id_child;
private String relation;
}
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json.toString(), User.class);
user.relations.foreach(r -> r.setUserParent(user));
userRepository.save(user);