英文:
define entity relationships just with id in body json Spring
问题
我正在尝试通过在CRUD中使用id来管理所有实体。
假设我有一个"Lesion(损伤)"实体和一个"Exam(检查)"实体。
AbstractEntity.java
@Getter
@Setter
@MappedSuperclass
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class AbstractEntity {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(unique = true, nullable = false)
private String id;
}
Lesion.java
@Entity
@Table(name = "lesion")
@Getter
@Setter
public class Lesion extends AbstractEntity {
@OneToMany(mappedBy = "lesion")
private List<Exam> exams;
}
Exam.java
@Entity
@Table(name = "exam")
@Getter
@Setter
public class Exam extends AbstractEntity {
@ManyToOne
public Lesion lesion;
}
我尝试通过检查id列表来在损伤和检查之间建立关系,例如:
(假设已经有2个持久化的检查,其id分别为e1afa296-05fe-4bc4-9103-0f0bb6a5cedd
和97353d31-64ce-40f7-87ef-deab435a2f7c
)
POST <url>/lesion
body:
{
"exams": [
"97353d31-64ce-40f7-87ef-deab435a2f7c",
"e1afa296-05fe-4bc4-9103-0f0bb6a5cedd"
]
}
目前,我能做的最好的方式是:
POST <url>/lesion
body:
{
"exams": [
{"id": "97353d31-64ce-40f7-87ef-deab435a2f7c"},
{"id": "e1afa296-05fe-4bc4-9103-0f0bb6a5cedd"}
]
}
然后手动获取与这些id对应的持久化对象,并在损伤中手动设置它们。
我确信通过Jackson有一种更自动化的方法,但我被卡住了。
你有什么想法吗?
谢谢。
英文:
I'm trying to manage all my entities through id in CRUD.
Let's say I have Lesion entity and Exam entity.
AbstractEntity.java
@Getter
@Setter
@MappedSuperclass
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class AbstractEntity {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(unique = true, nullable = false)
private String id;
}
Lesion.java
@Entity
@Table(name = "lesion")
@Getter
@Setter
public class Lesion extends AbstractEntity {
@OneToMany(mappedBy = "lesion")
private List<Exam> exams;
}
Exam.java
@Entity
@Table(name = "exam")
@Getter
@Setter
public class Exam extends AbstractEntity {
@ManyToOne
public Lesion lesion;
}
I try to set relationship between lesion and exam through exam id list, like :
(imagine there are already 2 persisted exam with id e1afa296-05fe-4bc4-9103-0f0bb6a5cedd
and 97353d31-64ce-40f7-87ef-deab435a2f7c
)
POST <url>/lesion
body:
{
"exams": [
"97353d31-64ce-40f7-87ef-deab435a2f7c",
"e1afa296-05fe-4bc4-9103-0f0bb6a5cedd"
]
}
For now, the best I can do is :
POST <url>/lesion
body:
{
"exams": [
{"id": "97353d31-64ce-40f7-87ef-deab435a2f7c"},
{"id": "e1afa296-05fe-4bc4-9103-0f0bb6a5cedd"}
]
}
and manually get the persisted objects corresponding to these ids and set them manually in lesion.
I'm sure there is a more automatic way through Jackson but I'm stuck.
Have you an idea ?
Thank you.
专注分享java语言的经验与见解,让所有开发者获益!
评论