'MantToMany - Cannot add or update a child row: a foreign key constraint fails
I am trying to create Many to Many relationship and save some data to database. I have entities:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class UnifiedOfferEntity {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String idOffer;
private String companyName;
private String city;
private String street;
private String title;
private LocalDateTime posted;
private String url;
private boolean remote;
private boolean remoteRecruitment;
@ManyToMany
@JoinTable(
name = "terms_of_contract",
joinColumns = @JoinColumn(name = "offer_id"),
inverseJoinColumns = @JoinColumn(name = "contract_id"))
private Set<ContractDetailsEntity> contractDetails = new HashSet<>();
}
@Entity
@Data
@Table(name = "ContractDetails")
@AllArgsConstructor
@NoArgsConstructor
public class ContractDetailsEntity {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@Enumerated(EnumType.STRING)
private TypeOfContract typeOfContract;
private double salaryFrom;
private double salaryTo;
@ManyToMany(mappedBy = "contractDetails")
private Set<UnifiedOfferEntity> unifiedOffers = new HashSet<>();
}
And when I want to save something I am getting that execption and I do not know what is wrong:
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`jobfinder`.`terms_of_contract`, CONSTRAINT `FKfyi46wtjxm9cmb5fh28lf47qt` FOREIGN KEY (`contract_id`) REFERENCES `contract_details` (`id`))
Solution 1:[1]
Try to map you entity like this way
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(
name = "terms_of_contract",
joinColumns = @JoinColumn(name = "offer_id"),
inverseJoinColumns = @JoinColumn(name = "contract_id"))
private Set<ContractDetailsEntity> contractDetails = new HashSet<>();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Diallo Mamadou Pathé |