How do you Set Up a Many-to-Many Relationship with Junction Table using JPA/EclipseLink

后端 未结 1 1961
清歌不尽
清歌不尽 2021-01-14 06:03

I have 2 tables:

Movies: movieID

Users: userID

These tables have a many to many relationship through the Queue table, with an additional attribut

相关标签:
1条回答
  • 2021-01-14 06:42

    First of all, as suggested by Mike Cornell, the EmbeddedId/Class is probably the easier-to-use choice. Nonetheless, to answer to your question and corrected code:

    @IdClass(QueueItemPK.class)
    @Entity
    @Table(name="queue")
    public class QueueItem
    {
           @Id
           @ManyToOne(optional=false)
           @PrimaryKeyJoinColumn(name="movieID")
           private Movie movie;
    
           @Id
           @ManyToOne(optional=false)
           @PrimaryKeyJoinColumn(name="userID")
           private User user;
    
           @Basic
           private String listOrder;
    
           ...Getters/Setters...
    }
    
    public class QueueItemPK implements Serializable
    {
           private static final long serialVersionUID = 1L;
    
           @Id
           @Column(name="movieID")
           private Integer movie;
           @Id
           @Column(name="userID")
           private Integer user;
    
           ...Getters/Setter...
    
           public int hashCode()
           {
               return (movie.getMovieID() + "|" + user.getUserID()).hashCode();
           }
    
           public boolean equals(Object obj)
           {
               if (obj == this) return true;
               if (obj == null) return false;
               if (!(obj instanceof QueueItemPK)) return false;
               QueueItemPK pk = (QueueItemPK) obj;
               return pk.movie == movie 
                   && pk.user == user;
           }
    }
    

    As you can see it is neccessary that they have the type of the id's they've to match. not very beautiful, but working. And i suggest using generics for your Sets; makes ist easier to read and more secure to code.

    0 讨论(0)
提交回复
热议问题