我正在尝试制作一个简单的 Hibernate 示例。我有两个实体:用户和注释。他们有一对多的关系(一个用户可以有很多笔记)。请帮助我使用注释在数据库中正确显示这些关系。但我不想创建第三个表来实现关系。我需要只有两个表:
这是我的类(class):
用户.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:
@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();
}
}
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" />
在我的数据库中执行此代码后,Hibernate 已创建并填充了两个表:
但是我遇到了一个问题:note表中的字段user_id值为null。虽然它必须等于用户id(在本例中为1)。
我需要在注释中添加什么才能解决这个问题,这个例子才能正常工作?但无需创建额外的表。
如果有任何帮助,我将不胜感激!
最佳答案
您必须在每个注释中设置 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);
关于java - hibernate 。如何正确组织带有注释的一对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9560522/