Reputation: 725
Hello guys I do have a following code:
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
}
and this entity also:
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
}
This is the test I'm doing to use the snippets:
@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);
}
Im using the standart CRUD repositories and the result of this is that I have a records in both Patient and Doctor tables, but the table doctor_patient is empty and never gets inserted with the correct data. How to fix that ?
Upvotes: 2
Views: 659
Reputation: 6254
Remove @Transactional
it is rolling back that transaction..use below you should be good.
@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);
}
Upvotes: 2
Reputation: 725
Due to the fact that I've added a @Transactional in the test description Hibernate was rolling back the result.Now after I remove it it works like a charm.
Upvotes: 0