0

I am working on a data model that basically consists of users and documents. Now everytime a new document is added, there should be a flag that identifies a document as "unseen" as long as the particular user did not had a look at it (e.g. clicked on it).

How would you model such a scenario ? Is there somehow a way to attach a boolean/flag to the relationship between users and documents ?

Here's my simplified model:

@Entity
@Table(name="User")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @Column(length = 128)
    private String name;
    @ManyToMany(mappedBy = "users", fetch=FetchType.LAZY)
    private List<Document> documents = new ArrayList<Document>();

    // getters and setters ...

}

Here's the document class:

@Entity
@Table(name = "Document")
public class Document {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name = "Inbox", joinColumns = @JoinColumn(name = "document_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
    protected List<User> users = new ArrayList<User>();

    // getters and setters ...

}

Many thanks for your help!

salocinx
  • 3,715
  • 8
  • 61
  • 110
  • 1
    You seem to need an additional column in your join table, viewed. Hence, you will need to split your many-to-many into two one-to-many/many-to-one relationships. – skuntsel Feb 26 '13 at 17:45
  • Thanks for your fast answers! I'll try your suggestions and come back as soon as possible. – salocinx Feb 26 '13 at 18:33

2 Answers2

1

Add a new column to your Inbox join table stores the "unseen" boolean. Then map the join table as new entity, and decompose the many-to-many association into two OneToMany associations.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

In the answer by JB Nizet that Matt made reference to the join table has a unique primary key (id), one unique constraint on the two foreign keys and an additional column. This is a good way to go.

But as you are useing @ManyToMany you are most likely to have a primary key which consists of two foreign keys in the join table. In case you'll want to stay with that pattern and add an extra viewed column, you will most likely need to get accustomed to using @Embeddable classes to have the composite primary key reflected in your @Entity. Remember, when you do it like this, you will need to override equals/hashcode.

You can see my answer on the other question as a staring point to creating your @Entity classes. In the answer the entity from the joined table is described, as well as its primary key.

Community
  • 1
  • 1
skuntsel
  • 11,624
  • 11
  • 44
  • 67