1
Package com.bjsxt.hibernate;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.GenerationType;
Import Javax.persistence.Id;
Import javax.persistence.Inheritance;
Import Javax.persistence.InheritanceType;
Import Javax.persistence.TableGenerator;
@Entity
@Inheritance (strategy=inheritancetype.table_per_class)
@TableGenerator (
name= "T_gen"),
table= "T_gen_table",
pkcolumnname= "T_PK",
valuecolumnname= "T_value",
pkcolumnvalue= " PERSON_PK ",
initialvalue=1,
allocationsize=1
) public
class Person {
private int id;
private String name;
@Id
@GeneratedValue (generator= "T_gen", strategy=generationtype.table) public
int GetId () {return
Id ;
}
public void setId (int id) {
this.id = ID;
}
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
}
2
Package com.bjsxt.hibernate;
Import javax.persistence.Entity;
@Entity public
class Student extends person {
private int score;
public int Getscore () {return
score;
}
public void SetScore (int score) {
this.score = score;
}
}
3
Package com.bjsxt.hibernate;
Import javax.persistence.Entity;
@Entity public
class Teacher extends person {
private String title;
Public String GetTitle () {return
title;
}
public void Settitle (String title) {
this.title = title;
}
}
4
Package com.bjsxt.hibernate;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.cfg.AnnotationConfiguration;
Import Org.hibernate.tool.hbm2ddl.SchemaExport;
Import Org.junit.AfterClass;
Import Org.junit.BeforeClass;
Import Org.junit.Test;
public class Hibernateormappingtest {private static sessionfactory sessionfactory; @BeforeClass public static void Beforeclass () {New Schemaexport () (New Annotationconfiguration (). Configure ()). Create (FAL
SE, true);
Sessionfactory = new Annotationconfiguration (). Configure (). Buildsessionfactory ();
@AfterClass public static void Afterclass () {sessionfactory.close ();
@Test public void Testsave () {Student s = new Student ();
S.setname ("S1");
S.setscore (80);
Teacher t = new Teacher ();
T.setname ("T1");
T.settitle ("intermediate");
Session session = Sessionfactory.opensession ();
Session.begintransaction ();
Session.save (s);
Session.save (t);
Session.gettransaction (). commit (); Session.cLose ();
@Test public void TestLoad () {testsave ();
Session session = Sessionfactory.opensession ();
Session.begintransaction ();
Student s = (Student) session.load (Student.class, 1);
System.out.println (S.getscore ());
Person P = (person) session.load (Person.class, 2);
System.out.println (P.getname ());
Session.gettransaction (). commit ();
Session.close (); @Test public void Testschemaexport () {New Schemaexport () (New Annotationconfiguration (). Configure ()). Create (False, T
Rue);
public static void Main (string[] args) {beforeclass ();
}
}