Reputation: 75
I've been trying to figure out how to get this to work with a Lazy fetch type, but I can't quite figure it out.
@Entity
@Table(name = "module")
public class Module extends ReservationOption{
@Column
private String name;
@Column
private int credits;
@Column
private int weeks;
@Column(name = "no_of_lectures")
private int noOfLectures;
@Column(name ="no_of_practicals")
private int noOfPracticals;
@Column(name = "lecture_length")
private int lectureLength;
@Column(name = "practical_length")
private int practicalLength;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "takes",
joinColumns = @JoinColumn(name = "moduleID"),
inverseJoinColumns = @JoinColumn(name = "studentID")
)
private Set<Student> students = new HashSet<>();
public void addTakes(Student student){
IDatabase db = Database.getInstance();
if(!db.checkInTable(Student.class, student.getId())) db.add(student);
Hibernate.initialize(students);
students.add(student);
student.getModules().add(this);
db.update(this);
}
@Entity
@Table(name = "student")
public class Student extends Person{
/**
* Constructor for Student class, allows for object creation
* @param id From Person
* @param firstName From Person
* @param lastName From Person
*/
public Student(String id, String firstName, String lastName) {
super(id, firstName, lastName);
}
/**
* Blank constructor to allow for database interfacing
*/
public Student(){
super();
}
@ManyToMany(mappedBy = "students", fetch = FetchType.LAZY)
private Set<Module> modules = new HashSet<>();
@Override
public Set<Module> getModules() {
return modules;
}
public void setModules(Set<Module> modules) {
this.modules = modules;
}
}
The error is being thrown on the line Hibernate.initialize(students); or on the next line if that isn't there, on the students set, with the error in the title. Any help (that's not just set fetch type to Eager) would be appreciated.
Upvotes: 1
Views: 3091
Reputation: 2393
Check the code path to make sure a Session is explicitly or implicitly (via Annotation, for example) created.
"No session" error usually means you're trying to call Hibernate behavior (i.e. Initialize, or just access a lazy variable) but there's NO Transaction/Session resources started up for it to operate within.
Usually when this happened to me in the past it was because it was plain java code that either hadn't set up Hibernate appropriately (hence, no Session existed to bolt on to) or I had set up Hibernate, but the code found a path in such a way that it never hit a @Transactional annotation, and therefore no Session was set up.
Upvotes: 2
Reputation: 36133
There are various options:
For details please read: https://thorben-janssen.com/5-ways-to-initialize-lazy-relations-and-when-to-use-them/
Upvotes: 1