user95040
user95040

Reputation:

Hibernate ManyToMany with Join table problems on update

I am trying to make a ManyToMany association work for all CRUD operations. I have two entities : Places and Events.

Places can hold multiple events, and an events can take place in multiple places.

In first case I had

In class 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:

@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

Second case
So after reading some docs, I changed PlaceDto to

@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.

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.

Christopher

Upvotes: 3

Views: 8648

Answers (1)

Gregory Mostizky
Gregory Mostizky

Reputation: 7261

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.

Upvotes: 5

Related Questions