简体   繁体   English

休眠。 如何正确组织一对多与注释的关系?

[英]Hibernate. How to properly organize relation a one-to-many with annotations?

I am trying to make a simple example of Hibernate. 我试图做一个简单的Hibernate示例。 I have two entities: User and Note. 我有两个实体:User和Note。 They have relation a one to many (one user can have a lot of notes). 它们具有一对多的关系(一个用户可以有很多笔记)。 Please help me to correctly display these relationships in a database using annotations.But I don't want to create third table for implementation of the relation. 请帮我使用注释在数据库中正确显示这些关系。但我不想创建第三个表来实现关系。 I need to have only two tables : 需要两张桌子 屏幕

Here are my classes: 这是我的课程:

User.java : User.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

Note.java : Note.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

Main.java : Main.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();
    }

}

hibernate.cfg.xml : hibernate.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" />

After executing this code in my database Hibernate has created and has filled two tables: 在我的数据库中执行此代码后,Hibernate创建并填充了两个表: 用户 注意

But I encounter a problem: the field user_id value is null in note table.Although it must be equal to the user id (in this case 1). 但是我遇到了一个问题:在note表中字段user_id值为null。虽然它必须等于用户id(在这种情况下为1)。

What do I need to add to annotations for to solve this problem and this example to work correctly? 我需要添加什么才能解决此问题以及此示例才能正常工作? But without creating additional tables. 但无需创建其他表。

I would really appreciate any help! 我真的很感激任何帮助!

You must set the User inside each note as you have defined a bidirectional relationship. 您已定义双向关系,因此必须在每个注释中设置User Instead of letting clients pass in a list of notes directly, create User.addNote and have it set the relationship correctly. 不要让客户端直接传入注释列表,而是创建User.addNote并让它正确设置关系。

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

Your test code thus becomes 你的测试代码就这样了

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);

You can further improve this by adding the basic fields to the constructors of your objects simplifying the above to 您可以通过将基本字段添加到对象的构造函数来进一步改进这一点,从而简化上述内容

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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