我正在尝试制作一个简单的 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)。
我需要在注释中添加什么来解决这个问题和这个例子才能正常工作?但无需创建额外的表。
我真的很感激任何帮助!