Hibernate级联保存

时间:2017-05-13 04:33:44

标签: java mysql hibernate jpa persist

我遇到了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:无法添加或更新子行:外键约束失败(sbbticketcomposition,CONSTRAINT {{ 1}} FOREIGN KEY(ticket)参考ticketIdticket))

我该如何解决这个问题?

1 个答案:

答案 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集,并且在此事务方法启动之前已保留该集。