• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to store composite objects in Hibernate

 
Shariq Roomi
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Entity
@Table(name="Teacher")

public class Teacher implements Serializable {
@Id
@Column(name="id")
private int id;

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

@OneToMany
@JoinColumn(name="id")
private List<Student> student;

//getter/setters
}

/////////////////////////////

@Entity
@Table(name="Student")

public class Student implements Serializable {

@Id
@Column(name="id")
private int id;

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

//getter/setters
}


And to store object, I am using

Teacher t1 = new Teacher();
t1.setId(10);
t1.setName("from hibernate");


Student s1 = new Student();
s1.setId(10);
s1.setStudentName("Student from hibernate");

List<Student> l = new ArrayList<Student>();
l.add(s1);

t1.setStudent(l);

getHibernateTemplate().save(t1);

The query generated by hibernate is

Hibernate: insert into Teacher (name, id) values (?, ?, ?)
Hibernate: update Student set id=? where id=?

Why am I getting update for student, this is a new object, Can any body please help me
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hibernate doesn't know what cascade option you want the relationship to use, you need to add that to your @OneToMany Annotation, basically cascade="CascadeType.PERSIST" or something like that, I don't remember the exact class and constant off the top of my head.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic