【问题标题】:Many to Many Spring Boot JPA not filling the ManyToMany Table多对多 Spring Boot JPA 未填充多对多表
【发布时间】:2019-02-26 16:06:54
【问题描述】:

大家好,我确实有以下代码:

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Doctor {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String firstName;
    private String lastName;
    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                    CascadeType.PERSIST,
                    CascadeType.MERGE
            })
    @JoinTable(name = "doctor_patient",
            joinColumns = {@JoinColumn(name="doctor_id")},
            inverseJoinColumns ={@JoinColumn(name="patient_id")})
    private Set<Patient> patients = new HashSet<>();


    //getters and setters
}

还有这个实体:

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Patient {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String firstName;
    private String lastName;
    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {
                    CascadeType.PERSIST,
                    CascadeType.MERGE
            },
    mappedBy = "patients")
    private Set<Doctor> doctorList = new HashSet<>();

    //Getters and setters

}

这是我正在做的使用 sn-ps 的测试:

@Test
@Transactional
public void testSaveDoctor(){

    Doctor firstDoctor = new Doctor();
    firstDoctor.setFirstName("test doc");
    firstDoctor.setLastName("lname doc");

    Patient firstPatient = new Patient();
    firstPatient.setFirstName("patient 1");
    firstPatient.setLastName("patient lname1");

    firstDoctor.getPatients().add(firstPatient);
    firstPatient.getDoctorList().add(firstDoctor);

    rDoctor.save(firstDoctor);
}

我正在使用标准的 CRUD 存储库,结果是我在 Patient 和 Doctor 表中都有记录,但是表 doctor_patient 是空的,并且永远不会插入正确的数据。 如何解决?

【问题讨论】:

    标签: java mysql spring hibernate orm


    【解决方案1】:

    删除@Transactional它正在回滚该事务..在下面使用你应该很好。

    @Test
    public void testSaveDoctor(){
    
        Doctor firstDoctor = new Doctor();
        firstDoctor.setFirstName("test doc");
        firstDoctor.setLastName("lname doc");
    
        Patient firstPatient = new Patient();
        firstPatient.setFirstName("patient 1");
        firstPatient.setLastName("patient lname1");
    
        firstDoctor.getPatients().add(firstPatient);
        firstPatient.getDoctorList().add(firstDoctor);
    
        rDoctor.save(firstDoctor);
    }
    

    【讨论】:

      【解决方案2】:

      由于我在测试描述中添加了一个@Transactional,Hibernate 正在回滚结果。现在在我删除它之后,它就像一个魅力。

      【讨论】:

      • 是的..发布了答案,但你做得很好
      猜你喜欢
      • 1970-01-01
      • 2020-03-29
      • 2020-05-12
      • 2021-08-25
      • 2018-02-26
      • 1970-01-01
      • 2016-01-09
      • 2021-07-12
      • 2015-09-27
      相关资源
      最近更新 更多