使用外键保存实体

时间:2018-07-18 22:51:19

标签: spring hibernate spring-mvc spring-data-jpa

我有一个问题,希望我能清楚地描述。我有以下课程:

@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
        }
      ]
    }

从技术上讲,我可以编写一个函数来做到这一点;但是,我觉得有一种更好更清洁的方法。

1 个答案:

答案 0 :(得分:0)

//convert json to java obj
Filter filter = new Gson().fromjson(yourjson, Filter.class);

//get the fiterMedication (id = 2)
int id = filter.getMedications().getId();
FilterMedication filterMedication = filterMedicationRepository.get(id);

Filter newFilter = new Filter();
newFilter.setId(filter.getId());
....//set name
newFilter.getMedications.add(filterMedication);//get the set of medications and add the element filterMedication

//save newFilter