0

I'm having an auto generated table by hibernate for the relationship between a User and Chat (a chat can have multiple users and a user can have multiple chats):

==User Model==
@Entity
public class User implements Serializable{

    @Id
    @GeneratedValue
    private int userId;
    private String username

==Chat Model==

@Entity
public class Chat implements Serializable{

    @Id
    @GeneratedValue
    private int chatId;
    private String subject;
    @ManyToMany
    private List<User> users;
    @ManyToOne
    private User created;

This generates a new table called Chat_User with the ID's of the user and the chat. Now I need another field (lastSeen) to be added in this generated table. How can this be realized? For now I have a new model that look's like the one below, but it is not working:

@Entity @Table(name = "Chat_User", catalog = "pdl") public class ChatUser implements Serializable {

    @Id
    @ManyToOne
    @JoinColumn(name="users_userId", nullable=false)
    private User user;

    @Id
    @ManyToOne
    @JoinColumn(name="Chat_chatId", nullable=false)
    private Chat chat;

    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    private Date lastSeen;

It will throw an exception: Unknown column 'lastSeen' in 'field list'. When I manually create this in the database it works somehow, but then it creates multiple entries (one with the lastSeen as value NULL and one with the correct value). Please help.

wesley
  • 137
  • 1
  • 2
  • 6
  • How do you insert values into these tables? Otherwise, the `@JoinTable` annotation does not allow you to specify extra columns, as far as I know. – Andrei Nicusan Dec 10 '13 at 15:46
  • Session session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); ChatUser chatUser = new ChatUser(); chatUser.setLastSeen(new Date()); chatUser.setChat(chat); chatUser.setUser(loggedInUser); session.save(chatUser); tx.commit(); – wesley Dec 10 '13 at 15:57

1 Answers1

0

You would need to create an Embedable Class and use the Association override to override the join table. Click here for a link to sample code by mkyong . Let me know if you need any more help.

Anugoonj
  • 575
  • 3
  • 9
  • Yeah well that tutorial was the first thing I tried. Gave me lot of problems... Isn't there any other way to do this? That tutorial seems very devious. – wesley Dec 10 '13 at 18:36
  • Well, I have referred that tutorial before and it works silky smooth. what problems were you facing using it ? – Anugoonj Dec 11 '13 at 11:14