1

我正在尝试制作一个简单的 Hibernate 示例。我有两个实体:用户和注释。它们具有一对多的关系(一个用户可以有很多笔记)。请帮助我使用注释在数据库中正确显示这些关系。但我不想创建第三个表来实现关系。我只需要两张桌子屏幕

这是我的课程:

用户.java

@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

@OneToMany(cascade = CascadeType.ALL, mappedBy="user") //Is it right value for  mappedBy-parameter?
private List<Note> notes = new ArrayList<Note>();

    // getters and setters

注意.java

@Entity
@Table(name = "note")
public class Note {

@Id
@GeneratedValue
@Column(name = "id")
private Long id;

@Column(name = "content")
private String content;

@ManyToOne
private User user;

    // getters and setters

主.java

public static void main(String[] args) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
        transaction = session.beginTransaction();

        List<Note> notes = new ArrayList<Note>();
        Note note1 = new Note();
        note1.setContent("my first note");
        Note note2 = new Note();
        note2.setContent("my second note");
        notes.add(note1);       
        notes.add(note2);   
        User user = new User();
        user.setName("Andrei");
        user.setNotes(notes);
        session.save(user);

        transaction.commit();
    } catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }

}

休眠.cfg.xml

<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    <property name="connection.pool_size">1</property>
    <property name="current_session_context_class">thread</property>
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="show_sql">true</property>        
    <property name="hbm2ddl.auto">create-drop</property>
    <mapping class="com.vaannila.blog.User" />
    <mapping class="com.vaannila.blog.Note" />

在我的数据库中执行此代码后,Hibernate 创建并填充了两个表: 用户 笔记

但是我遇到了一个问题:note表中的字段user_id值为null。虽然它必须等于用户id(在本例中为1)。

我需要在注释中添加什么来解决这个问题和这个例子才能正常工作?但无需创建额外的表。

我真的很感激任何帮助!

4

1 回答 1

3

您必须设置User每个音符的内部,因为您已经定义了双向关系。与其让客户直接传递笔记列表,不如创建User.addNote并正确设置关系。

class User {
    ...
    public void addNote(Note note) {
        note.user = this;
        notes.add(note);
    }
}

您的测试代码因此变成

Note note1 = new Note();
note1.setContent("my first note");
Note note2 = new Note();
note2.setContent("my second note");
User user = new User();
user.setName("Andrei");
user.addNote(note1);
user.addNote(note2);
session.save(user);

您可以通过将基本字段添加到对象的构造函数来进一步改进这一点,将上述内容简化为

User user = new User("Andrei");
user.addNote(new Note("my first note"));
user.addNote(new Note("my second note"));
session.save(user);
于 2012-03-05T01:28:57.197 回答