many-to-many-spring-boot-jpa不填充manytomy表

wf82jlnq  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(420)

大家好,我有以下代码:

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

}

这是我正在做的使用代码段的测试:

@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);
}

我使用的是standart crud存储库,结果是我在patient和doctor表中都有一个记录,但是doctor\u patient表是空的,永远不会插入正确的数据。怎么解决?

zrfyljdw

zrfyljdw1#

删除 @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);
}
qco9c6ql

qco9c6ql2#

由于我在测试描述中添加了@transactional,hibernate正在回滚结果。现在在我删除它之后,它就像一个符咒。

相关问题