ManyToMany表与额外的列Hibernate [英] ManyToMany table with extra column Hibernate

查看:117
本文介绍了ManyToMany表与额外的列Hibernate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个通过hibernate自动生成的用于聊天的聊天关系(聊天可以有多个用户,用户可以有多个聊天) pre> ==用户模型==
@Entity
public class User实现Serializable {

@Id
@GeneratedValue
private int userId;
私人字符串用户名

==聊天模式==

  @Entity 
public class Chat实现Serializable {

@Id
@GeneratedValue
private int chatId;
private String subject;
@ManyToMany
私人列表<用户>用户;
@ManyToOne
私人用户创建;

这将生成一个名为Chat_User的新表,其中包含用户和聊天的ID。现在我需要在此生成的表格中添加另一个字段(lastSeen)。这怎么能被实现?现在我有一个新的模型,看起来像下面的模型,但它不起作用:

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

@Id
@ManyToOne
@JoinColumn(name =users_userId,nullable = false)
私人用户用户;

@Id
@ManyToOne
@JoinColumn(name =Chat_chatId,nullable = false)
私聊对话;

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

它会抛出一个异常:'字段列表'中的未知列'lastSeen'。当我在数据库中手动创建它时,它会以某种方式工作,但它会创建多个条目(其中一个的lastSeen值为NULL,另一个值为正确值)。请帮助。

解决方案

您需要创建一个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.

这篇关于ManyToMany表与额外的列Hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆