简体   繁体   中英

ManyToMany table with extra column Hibernate

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM