在db中为User和Message之间的OneToMany关系创建NULL值

时间:2017-05-03 18:41:58

标签: java mysql hibernate

我正在尝试在User类和Message类之间创建OneToMany关系。用户可以拥有多条消息。但是当我在db中保留它时,我在表中得到Null值;

这是我的代码 的 User.java

@Entity
@Table
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String username;
    private String password;


    @OneToMany
    private List<Message> messages;

    public List<Message> getMessages() {
        return messages;
    }

    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }

    public User() {

    }
    public User(String userName, String password) {
        this.username = userName;
        this.password = password;
    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }


    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

Message.java

@Entity
public class Message {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @ManyToOne
    private User sender;
    private String receiver;
    private String content;


    @Type(type="timestamp")
    private Date created;

    public Message() {

    }


    public Message(String user, String receiver, String content) {
        this.sender = sender;
        this.receiver = receiver;
        this.content = content;
        this.created = new Date();
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public User getSender() {
        return sender;
    }

    public void setSender(User sender) {
        this.sender = sender;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

MessageDAOImpl.java

public class MessageDAOImpl implements MessageDAO {
    public static final Logger LOG = LoggerFactory.getLogger(MessageDAO.class);
    private static Session session;

    private static void beginSession() {
        session = DbUtils.getSessionFactory().openSession();
        session.beginTransaction();
    }

    @Override
    public void sendMessage(Message message) {
        beginSession();
        sendMessage(message, session);
        session.close();
    }

    public void sendMessage(Message message, Session session) {
      User user = new User();
      List<Message> list = new ArrayList<>();
      list.add(message);
        user.setMessages(list);

        try {
            session.save(user);
            session.save(message);
            session.getTransaction().commit();
        } catch (HibernateException e) {
            session.getTransaction().rollback();
            LOG.error("Cannot save the message", e);
        }
    }

MainClass 的 Solution.java

public class Solution {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Message message = new Message("HELP", "HELPER", "PLEASE HELP");
        MessageDAOImpl mess = new MessageDAOImpl();
        mess.sendMessage(message);
    }
}

这是在数据库中创建空条目。

mysql> select * from user;
   +----+--------------------------------------------------------------+-------------+
        | id | password                                                     | username    |
        +----+--------------------------------------------------------------+-------------+
        |  1 | $2a$10$.wjZcxcnyZV45cUhofl7gG64GYoekSOa | testUser123 |
        |  2 | NULL                                                         | NULL        |
        |  3 | NULL                                                         | NULL        |
        +----+--------------------------------------------------------------+-------------+

mysql> select * from Message;
+----+-----------------------------+---------------------+---------------------+-----------+
| id | content                     | created             | receiver            | sender_id |
+----+-----------------------------+---------------------+---------------------+-----------+
|  1 | This is good | 2017-05-03 11:17:27 | testReceivedFromCfg |      NULL |
|  2 | This challenge is good | 2017-05-03 11:28:25 | testReceivedFromCfg |      NULL |
|  3 | PLEASE HELP                 | 2017-05-03 11:35:22 | HELPER              |      NULL |
+----+-----------------------------+---------------------+---------------------+-----------+

mysql> select * from user_message;
+---------+-------------+
| User_id | messages_id |
+---------+-------------+
|       2 |           2 |
|       3 |           3 |
+---------+-------------+

我的问题是,用户可以发送多条消息。如果您直接致电sendMessage,则只有在message中出现senderreceier时才会发送User table。但是现在它用db值填充db。我该如何修改我的代码?

过程是 1) The user registers with username and password2) Sends message to receiver who is also in the db. 仅当发送方和接收方位于db中时才能发送消息。

1 个答案:

答案 0 :(得分:0)

您的代码似乎有点混乱。首先,你需要连接关系。

消息类

@OneToMany(mappedBy="sender")
@Fetch(value= FetchMode.JOIN)
private List<Message> messages = null;

在我的示例中,我通过User类的id连接两个实体。您仍然可以在数据库中使用不同的列。

用户类

@Transactional("hibernate")
@Override
public void updateMessage(Message transientObject) throws MyDaoException {
  Session session = getCurrentSession();
  session.save(message);
}

添加所需的cascadeTypes并根据需要更改FetchMode。添加其他参数。

<强> DAO

首先,删除所有不属于DAO的代码。通常,db-Entry的更新可以看起来像这样简短:

var dog = {
  name:'Rex'
}

用户相同。