Create a hibernate.cfg.xml file first, then add a line for mapping
< mapping class ="demo.terrytsao.model.StudentInfo " />
import javax .persistence .*;
@ Entity
@ Table (name ="SomeTableNameIfYouDontWantItToBeTheDefaultClassName" )
public class StudentInfo {
@ Id @ GeneratedValue (strategy = GenerationType .AUTO )
private int rollNo ;
@ Column (name ="username" , nullable =false )
private String name ;
@ Transient
private String attrToIgnore ;
@ Temporal (TemporalType .DATE )
private Date dateWithoutTime ;
// the rest
}
public class Main {
public static void main (String [] args ) {
StudentInfo student = new StudentInfo ();
SessionFactory sf = new AnnotationConfiguration ().configure ();
Session sss = sf .openSession ();
sss .beginTransaction ();
sss .save (student );
sss .getTransaction ().commit ();
sss .close ();
sf .close ();
}
}
@ Entity
public class Student {
@ Id @ GeneratedValue
private int id ;
}
@ Entity
public class StudentDetail {
@ Id @ GeneratedValue (generator = "newGenerator" )
@ GenericGenerator (name ="newGenerator" , strategy = "foreign" ,
parameters = {@ Parameter (value = "student" , name ="property" )})
private int id ;
@ OneToOne (cascade = CascadeType .ALL )
@ JoinColumn (name = "student_id" )
private Student student ;
}
// in main, save studentDetail object after setStudent method call
@ Entity
public class Student {
@ Id @ GeneratedValue
private int id ;
@ ManyToOne (cascade = CascadeType .ALL )
private StudentAddress studentAddress ;
// getters and setters
}
@ Entity
public class StudentAddress {
@ Id @ GeneratedValue
private int id ;
// for bidirection
@ OneToMany (cascade = CascadeType .ALL , mappedBy = "studentAddress" )
private Set <Student > students = new HashSet <>(0 );
// getters and setters
}
// in main, save student object
@ Entity
public class Student {
@ Id @ GeneratedValue
private int id ;
@ ManyToMany (cascade = CascadeType .ALL )
private Set <StudentCert > studentCert = new HashSet <>(0 );
// getters and setters
}
@ Entity
public class StudentCert {
@ Id @ GeneratedValue
private int id ;
// for bidirection
@ ManyToMany (cascade = CascadeType .ALL , mappedBy = "studentCert" )
private Set <Student > students = new HashSet <>(0 );
// getters and setters
}
public static void main (String [] args ) {
// Save
session .save (student );
// Get
student = (Student ) session .get (Student .class , 1 );
// Update
student .setSth ("Sth" );
session .update (student );
// Delete
session .delete (student );
}