Suppose I have two database tables
Course { Course_no(PK), course_name, student_id (FK refers to "Student") }
Student { id (PK), name }
each student can take many courses so it is a many-to-one relation from "Course" to "Student". Suppose we don't want any delete cascade function being implemented. I am thinking about two ways to use hibernate to implement but not sure if both work.
***************************************
approach 1) Use no direction association in POJO
Class Course {
private int course_no;
private
String course_title;
private int student_id;
}
class Student {
private int id;
private String name;
}
In the <hibernate-mapping> we don't have any <many-to-one> xml.
approach 2) Use association in POJO
class course {
private int course_no;
private String course_title;
private Studetn student;
}
class Student {
private int id;
private String name;
}
In the <hibernate-mapping> we have
<many-to-one
name="student" column="student_id" class="Student" foreign-key="fk_student"/>
*********************************************
It seems most books use the 2nd approach. But I found that when I use the 1st approach without having that <many-to-one> xml section in <hibernate-mapping>, it works fine for me. I can insert and update "course" and "student" tables separately. The database itself has its foreign constraint set up so I don't need to worry about the the constraint. Plus, if I try to insert a "course" object, I don't have to create a "student" object first (like in the 2nd approach) before I can save(course).. As long as I know the "student_id", just simply create the course object itself and save it to the table.
Does the 1st approach work ?
Thank you.