Hi.
I discovered a strange behaviuor of Hibernate's Session when inserting 2 objects which shares the same proxy property.
The example:
I have 2 classes: Student and Teacher:
Quote:
@Entity
@Table(name = "Z_TEACHER")
public class Teacher {
private Long id;
private String name;
private List<Student> students;
@Id
@Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "teacher")
public List<Student> getStudents() {
System.out.println("getStudents called ; id= " + getId());
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
..
}
Code:
@Entity
@Table(name = "Z_STUDENT")
public class Student {
private Long id;
private String name;
private Teacher teacher;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(Teacher teacher) {
super();
this.teacher = teacher;
}
@Id
@Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TID")
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
...
}
I want to insert 2 students using the same Teacher , load as a proxy by Id. When the first student is inserted everything is ok, but when the second student is inserted the teacher is materialized from the database; That's because the hashCode() of Teacher object is called (due of some ordering of entities in the session) and the hashCode() method is overridden in the classes.
Code:
public void testProxiesInBatch()
{
Teacher t = testDao.getByIdAsProxy(new Long(1));
Student s = new Student(t);
s.setId(new Long(1));
s.setName("QQ");
testDao.saveStudent(s);
s = new Student(t);
s.setId(new Long(2));
s.setName("PP");
testDao.saveStudent(s);
}
First I 'm surprised by this behaviour, cause Hibernate documentation doesn't mention anything about it. And my question is: Is it absolutely normal? Should we try to avoid the read from the database or the fact that the teacher is materialized is an issue Hibernate MUST do?
Thank you
Cristi