I have 2 entity class called Student and University and relationship between student and university is Many-to-one which means many students can study in one university. My input jsp page basically will ask the university name and student email address to register.
Here is the flow. I enter following in my input page -
university1, student1 - This will add university1 and student1 in my database.
When I enter -
university1, student2 - My intention here is to first find whether university1 is already present in my database. If it is then associate the same university to student object and try to save it. But when I am doing that hibernate is trying to add one more university object in the database and I am getting following exception -
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'university_id'.
Here are my entity classes -
@Entity
@Table(name="students")
public class Student implements Serializable{
private Integer studentId;
private University university;
@Id
@GeneratedValue
@Column(name = "student_id")
public Integer getStudentId() {
return studentId;
}
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "university_id")
public University getUniversity() {
return university;
}
}
@Entity
@Table(name="university")
public class University implements Serializable {
private Integer universityId;
@Id
@GeneratedValue
@Column(name = "university_id")
public Integer getUniversityId() {
return university;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
@Column(name = "university_name", unique = true, nullable = false)
public String getUniversityName() {
return university;
}
}
Here is the simple Java Code.
University university = universityService.getUniversityByName(student.getUniversity().getUniversityName());
if(university != null) {
student.setUniversity(university);
}
getHibernateTemplate().saveOrUpdate(student);
I am using Spring MVC and database schema is getting generated by Hibernate. Looks like I am making some very basic mistake.