ID生成策略之聯合主鍵xml實現

Student.hbm.xml的配置:

<hibernate-mapping package="org.hibernate.first.model">


<class name="Student">

<composite-id name="pk" class="org.hibernate.first.model.StudentPK">  

<key-property name="id"></key-property>   <!--主鍵屬性-->

<key-property name="name"></key-property>   <!--主鍵屬性-->

</composite-id>


        <property name="age" column="age"/>   <!--剩餘的其他屬性-->

   </class>


</hibernate-mapping>


主鍵類的編寫:

public class StudentPK implements Serializable{

private int id;

private String name;

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;

}

@Override

public boolean equals(Object o){

if (o instanceof StudentPK) {

StudentPK pk = (StudentPK)o;

if (this.id == pk.getId() && this.name.equals(pk.getName())) {

return true;

}

}

return false;

}

@Override

public int hashCode(){

return this.name.hashCode();

}

}


model類的編寫:

public class Student {

private int age;

private StudentPK pk;

public StudentPK getPk() {

return pk;

}

public void setPk(StudentPK pk) {

this.pk = pk;

}


public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

}


測試類的編寫:

public class TestStudent {

static Configuration cfg = null;

static SessionFactory sessionFactory = null;

@Before

public void before(){

System.out.println("this is before");

}

@BeforeClass

public static void beforeClass(){

cfg = new AnnotationConfiguration();

sessionFactory = cfg.configure().buildSessionFactory();

}

@Test

public void testStudent(){

Student s = new Student();

StudentPK pk = new StudentPK();

pk.setId(1);

pk.setName("jim");

s.setPk(pk);

//s.setName("jim");

s.setAge(20);

Session session = sessionFactory.openSession();

session.beginTransaction();

session.save(s);

session.getTransaction().commit();

session.close();

}

@After

public void after(){

System.out.println("this is After.");

}

@AfterClass

static public void afterClass(){

sessionFactory.close();

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章