简体   繁体   中英

Unable to save parent and child in single transaction in hibernate spring boot

I have one to many unidirectional mapping

Employer entity

@OneToMany(cascade= CascadeType.ALL)
@JoinColumn(name="employer_id")
privae List<Employee> empDetails =  new ArrayList<>();

Employee entity

@Column(name = "employer_id")
private int employerId

From postman while sending both the parent and child entity am gettin exception like "Cannot add or update child entity foreign contrarian fails ". My question is like is it mandatory to make bidirectional to save parent and child in single transaction??

Not necessarily.

Bidirectional mapping is required where you want to save the child entity and you want the parent entity to also be saved.

Ex: Unidirectional mapping

@Repository
public interface IEmployer extends JpaRepository<Employer, Long> {
}
@Component
public class Employer implements IEmployer {

@Autowired
private IEmployer empRepo;

List<Employee> listEmployee = new ArrayList<>();
Employer employer = new Employer();

Employee employee = new Employee();
employee.setId(100);
listEmployee.add(employee);

employer.setEmpoyee(listEmployee);

empRepo.save(employer); //JPA repo save

}

Remove

@Column(name = "employer_id")
private int employerId

from your Employee class (because it is not how you do unidirectional mapping, if you need the id, then do bidirectional mapping, what you are doing right now is a mix of both, which doesn't work).

For saving, add the Employee object (s) to your Employer object and then save the employer. You do not have to save the employee (s) anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM