[英]Hibernate cascade save
I have a problem with Hibernate. 我对Hibernate有问题。 See my data model 查看我的数据模型
I have class - "Ticket"... 我上课-“票” ...
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "ticketComposition",
joinColumns = { @JoinColumn(name = "ticketId")},
inverseJoinColumns = { @JoinColumn(name = "tripsSiteId")})
private Set<TripsSite> tripsSites = new HashSet<TripsSite>();
and when I'm trying to save new ticket... 当我试图保存新票时...
Ticket ticket = new Ticket();
User user = userService.findBySSO(userName);
ticket.setUser(user);
ticket.setTripsSites(new HashSet<>(tripsSites));
persist(ticket);
I get the following error: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails ( sbb
. ticketcomposition
, CONSTRAINT ticket
FOREIGN KEY ( ticketId
) REFERENCES ticket
( id
)) 我得到以下错误:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:不能添加或更新子行,外键约束失败( sbb
。 ticketcomposition
,约束ticket
外键( ticketId
)参考文献ticket
( id
))
How can i resolve this problem? 我该如何解决这个问题?
Assuming you have something like this defined on the TicketSite
entity: 假设在TicketSite
实体上定义了以下TicketSite
:
@ManyToMany(mappedBy="tripSites")
private Set<Trip> trips = new HashSet<Trip>();
While persisting, you have to set the dependencies on both sides of the @ManyToMany
mapping: 持久化时,必须在@ManyToMany
映射的两侧设置依赖@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);
I am assuming that the ticketSites
set has been previously retrieved from the database and has been persisted before this transactional method started. 我假设ticketSites
集合先前已从数据库中检索到,并且在此事务处理方法开始之前已经存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.