Reputation: 73
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 ??
Upvotes: 0
Views: 1454
Reputation: 126
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
}
Upvotes: 1
Reputation: 499
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.
Upvotes: 0