且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ManyToMany表与额外的列Hibernate

更新时间:2023-12-01 14:30:04

您需要创建一个Embedable Class并使用Association覆盖来覆盖连接表。 点击此处查看链接示例代码由mkyong 。让我知道你是否需要任何帮助。


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.