I am learning Hibernate relationships and have two classes:
@Entity
@Table(name = "students")
public class Student {
@Id
private int sid;
@OneToMany(mappedBy = "student")
private List<Laptop> laptops = new ArrayList<>();
//getters and setters
}
and
@Entity
@Table(name = "laptops")
public class Laptop {
@Id
private int lid;
private String lName;
@ManyToOne
private Student student;
//getters and setters
}
I create Student object, add to it two Laptop objects and save it like that:
Laptop lap1 = new Laptop();
lap1.setLid(101);
lap1.setlName("Dell");
Laptop lap2 = new Laptop();
lap2.setLid(102);
lap2.setlName("HP");
Student stud1 = new Student();
stud1.setName("Mark");
stud1.setSid(1);
stud1.getLaptops().add(lap1);
stud1.getLaptops().add(lap2);
Transaction transaction = session.beginTransaction();
session.save(lap1);
session.save(lap2);
session.save(stud1);
transaction.commit();
However when I execute SELECT * FROM laptops
after, I see student_sid
column which references sid
in students
table, but it contains NULL values. What did I do wrong?
By the way, I am able to fetch student object using session.get
and it contains laptops in it (I suspect it is Hibernate cache).
CodePudding user response:
You are responsible for maintaining the relationships between your entities. The most likely explanation here is that you never setup proper relationships between the student and its laptops. Consider this version:
// first setup laptops for the student
Student stud1 = new Student();
Laptop lap1 = new Laptop();
Laptop lap2 = new Laptop();
List<Laptop> laptops = new ArrayList<>();
laptops.add(lap1);
laptops.add(lap2);
stud1.setLaptops(laptops);
// now set the reverse relationships
lap1.setStudent(stud1);
lap2.setStudent(stud1);
To avoid repetitive code, you may add methods to your two entity classes which manage this relationship bookkeeping.
CodePudding user response:
From what I can see you could be missing the @JoinColumn
annotation under the @ManyToOne
.
Your Laptop class should look something like:
@Entity
@Table(name = "laptops")
public class Laptop {
@Id
private int lid;
private String lName;
@ManyToOne
@JoinColumn("student_id")
private Student student;
}
and Student:
@Entity
@Table(name = "students")
public class Student {
@Id
@Column(name = "student_id")
private int sid;
@OneToMany(mappedBy = "student")
private List<Laptop> laptops = new ArrayList<>();
}
Don't forget to be aware of the fetch type (eager/lazy) and cascade type in the relation; also before you save the student, you should set the list of laptops.