【发布时间】:2018-07-18 22:51:19
【问题描述】:
我有一个问题希望我能清楚地描述。我有以下课程:
@Entity
public class Filter {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,orphanRemoval = true)
@JoinColumn(name = "filter_id", nullable = false)
private Set<FilterMedication> medications;
//setter and getters are not show
...}
.
@Entity
public class FilterMedication {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne
@JoinColumn(name = "medication_id", nullable = false)
private Medication medication;
// Setters and getters are not shown
.....}
.
@Entity
@Table(name = "medication")
public class Medication {
@Column(name = "generic_name")
private String genericname;
private String name;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
// Setters and getters are not shown
.....}
基本上过滤与FilterMedicaton的一对多关系,FilterMedication与Medication是多对一的关系。
我创建了一个存储库来查询过滤器
public interface FilterRepository extends JpaRepository <Filter, Long> {}
我可以通过将以下 JSON 对象发送到 save() 函数来添加新过滤器
{
"id": 1,
"name": "Test1",
"medications": [
{
"id": 2,
"medication": {
"genericname": "Oxymetazoline HCl Nasal Soln 0.05%",
"name": "12 HOUR NASAL SPRAY 0.05 % NA SOLN",
"strength": "0.05%",
"form": "Solution",
"route": "Nasal"
}
}
]
}
现在是时候提出问题了:有没有办法传递药物外键而不是完整的药物对象,Spring JPA 会将外键转换为正确的对象? JSON 代码将是这样的
{
"id": 1,
"name": "Test1",
"medications": [
{
"id": 2,
"FORIGEN KEY": 1
}
]
}
从技术上讲,我可以编写一个函数来做到这一点;但是,我觉得有一种更好、更清洁的方法。
【问题讨论】:
标签: spring hibernate spring-mvc spring-data-jpa