I am trying to make a simple example of Hibernate. I have two entities: User and 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:
@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
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:
<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:

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).
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
Userinside each note as you have defined a bidirectional relationship. Instead of letting clients pass in a list of notes directly, createUser.addNoteand have it set the relationship correctly.Your test code thus becomes
You can further improve this by adding the basic fields to the constructors of your objects simplifying the above to