我遇到了Hibernate的问题。 见my data model
我上课 - “门票”......
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "ticketComposition",
joinColumns = { @JoinColumn(name = "ticketId")},
inverseJoinColumns = { @JoinColumn(name = "tripsSiteId")})
private Set<TripsSite> tripsSites = new HashSet<TripsSite>();
当我试图保存新票时......
Ticket ticket = new Ticket();
User user = userService.findBySSO(userName);
ticket.setUser(user);
ticket.setTripsSites(new HashSet<>(tripsSites));
persist(ticket);
我收到以下错误:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(sbb
。ticketcomposition
,CONSTRAINT {{ 1}} FOREIGN KEY(ticket
)参考ticketId
(ticket
))
我该如何解决这个问题?
答案 0 :(得分:0)
假设您在TicketSite
实体上定义了类似的内容:
@ManyToMany(mappedBy="tripSites")
private Set<Trip> trips = new HashSet<Trip>();
在持久化的同时,您必须在@ManyToMany
映射的两端设置依赖关系:
Ticket ticket = new Ticket();
User user = userService.findBySSO(userName);
ticket.setUser(user);
ticket.setTripsSites(new HashSet<>(tripsSites));
for(TicketSite ticketSite: ticketSites){
ticketSite.getTickets().add(ticket);
}
persist(ticket);
我假设先前已从数据库中检索ticketSites
集,并且在此事务方法启动之前已保留该集。