1

I want to create M:N relationship as below enter image description here

  • Each user can have zero or many ebooks

  • Each ebook must belongs to one or many users

My mappings in Hibernate :

User.java

@Entity
@Table(name = "USERS")
public class User {
//...
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "USER_EBOOK", joinColumns = @JoinColumn(name = "USER_ID", nullable = false),
           inverseJoinColumns = @JoinColumn(name = "EBOOK_ID", nullable = false))   
private List<Ebook> listOfEbooks = new ArrayList<Ebook>();
//...
}

Ebook.java

@Entity
@Table(name="EBOOK")
public class  Ebook {
//...
@ManyToMany(mappedBy = "listOfEbooks", fetch = FetchType.EAGER)  
@NotFound(action = NotFoundAction.EXCEPTION)    
private List<User> listOfEbookUsers = new ArrayList<User>();
//...
}

How can I add this additional constraints for example one or many - zero or many?, when I save only ebook object to database there is ebook that does not belongs to anyone.

piczaj
  • 424
  • 1
  • 8
  • 21
  • Have you tried to create setters with extra logic? – Khozzy Nov 08 '13 at 09:27
  • I have default generated setters .. hmm how exactly you get the idea to prevent before adding e.g ebook which doesn't have owner ?, in other words to make one or many, hibernate creates zero or many from what I see – piczaj Nov 08 '13 at 15:24
  • this is a strange set of requirements. an ebook entity can only exist if it's associated with a user? what happens if i want to create an ebook A an if none of the users own the ebook A? is there at least a concept of a _default_ user? – Dexter Legaspi Sep 18 '21 at 14:06

1 Answers1

0

See this question and the answer of the thread:

And see also this tutorial:

The tutorial provides very good examples of how to implement a proper Many-to-Many mapping.

Community
  • 1
  • 1
L.Butz
  • 2,466
  • 25
  • 44