简体   繁体   English

Hibernate ManyToMany在更新时出现连接表问题

[英]Hibernate ManyToMany with Join table problems on update

I am trying to make a ManyToMany association work for all CRUD operations. 我正在努力使ManyToMany协会适用于所有CRUD操作。 I have two entities : Places and Events . 我有两个实体: PlacesEvents

Places can hold multiple events, and an events can take place in multiple places. 地方可以举办多个活动,活动可以在多个地方举行。

In first case I had 在第一种情况下,我有

In class PlaceDto 在PlaceDto课程中

@ManyToOne(  
    targetEntity=EventDto.class,  
    cascade = { CascadeType.PERSIST, CascadeType.MERGE })  
@JoinTable(  
    name = "EVENTS_PLACES",  
    joinColumns = { @JoinColumn(name = "PLACE_ID") },  
    inverseJoinColumns = { @JoinColumn(name = "EVENT_ID") })  
private List<EventDto> events;

In class PlaceDto: 在PlaceDto类中:

@JoinTable(name = "EVENTS_PLACES", joinColumns = @JoinColumn(name = "EVENT_ID"), inverseJoinColumns = @JoinColumn(name = "PLACE_ID"))
private List<PlaceDto> places;

in this case on updating a place the link between the place and its event was erased 在这种情况下,在更新地点时,地点与其事件之间的链接被删除
with DELETE FROM EVENTS_PLACES where ... statement 使用DELETE FROM EVENTS_PLACES where ...语句

Second case 第二种情况
So after reading some docs, I changed PlaceDto to 所以在阅读了一些文档后,我将PlaceDto更改为

@ManyToMany (
   mappedBy = "events",  
   cascade = { CascadeType.PERSIST, CascadeType.MERGE },  
   fetch = FetchType.LAZY,  
   targetEntity = FundDto.class)  
private List<PlaceDto> places;

When updating a place everything seems to be fine, but when I try to create an event, it tries also to create a place 当更新一个地方时,一切似乎都很好,但是当我尝试创建一个事件时,它也会尝试创建一个地方
=> which leads to a primary key violation. =>这会导致主键违规。

I have hashcode() and equals() overridden using eclipse. 我使用eclipse覆盖了hashcode()和equals()。

Thanks for your help. 谢谢你的帮助。

Please do not hesitate to point me to a page where a fully working and tested ManyToMany relation is shown and explained. 请不要犹豫,向我指出一个页面,其中显示和解释了完全工作和测试的ManyToMany关系。

Christopher 克里斯托弗

Here is a nice example 这是一个很好的例子

Just try to copy what they have there into your own code and it should work. 只是尝试将他们拥有的内容复制到您自己的代码中,它应该可以工作。 If it still doesn't, please post full listings for two classes and the code that causes the error and maybe I can see what the problem is. 如果它仍然没有,请发布两个类的完整列表和导致错误的代码,也许我可以看到问题是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM