Hi All,
I am very much new to hibernate . So may be beginner level question .
I have two Pojo
1. Student
2. Course
and both are having many to many relationship.
Now I want to assign existing student to new course. For eg if User_A is already there and assigned a course of Java and now I want to assign same user with
course of Hibernate.
What I am doing is : I have create a jsp page which contains following fields
Fname
lname
drop down of course fetched from DB using hibernate
So after submitting this page I wrote following code
Code:
openHibernaeSession();
Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.eq("fname",student.getFname())).add(Restrictions.eq("lname",student.getLname()));
if(criteria.list().size()!=0) {
Student tempStudent = (Student) criteria.list().get(0);
student.setId(tempStudent.getId());
tempStudent = null;
}
closeHibernateSession();
openHibernaeSession();
session.update(student);
closeHibernateSession();
Student.java is
Code:
package com.hibernateproject;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
@Entity
public class Student {
@Id
@GeneratedValue
private int id;
private String fname;
private String lname;
@ManyToMany
@JoinTable(
joinColumns=@JoinColumn(name="userId"),
inverseJoinColumns = @JoinColumn(name="courseId")
)
private Collection <Course> listOfCourse = new ArrayList<Course>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Collection<Course> getListOfCourse() {
return listOfCourse;
}
public void setListOfCourse(Collection<Course> listOfCourse) {
this.listOfCourse = listOfCourse;
}
}
course.java is
Code:
package com.hibernateproject;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class Course {
@Id @GeneratedValue
private int id;
private String courseName;
@ManyToMany(mappedBy="listOfCourse")
private Collection<Student> listOfStudent = new ArrayList<Student>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public Collection<Student> getListOfStudent() {
return listOfStudent;
}
public void setListOfStudent(Collection<Student> listOfStudent) {
this.listOfStudent = listOfStudent;
}
}
But it is not working . it is not updating any thing . Please guide me.