Xml:composite-id
To override the Equals,hashcode method, also serialize the
1. Create a new primary key class: Studentpk.java, note that serialization is required. Also rewrite equals and hashcode:
Package Com.bjsxt.hibernate;public class STUDENTPK implements java.io.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;} @Overridepublic 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;} @Overridepublic int hashcode () {return This.name.hashCode ();}}
2. Delete the ID in Student.java and the set and get method of name, create a new primary key object and setter and getter:
Package Com.bjsxt.hibernate;public class Student {private studentpk pk;private int age;public studentpk GETPK () {return PK ;} public void Setpk (STUDENTPK pk) {this.pk = PK;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}
3. JUnit's test method is changed to:
@Testpublic void Teststudentsave () {STUDENTPK pk=new studentpk ();p K.setid (1);p k.setname ("Zhangsan"); Student s =new Student (); S.SETPK (PK); S.setage (23); Session session = sf.opensession (); Session.begintransaction (); Session.save (s); Session.gettransaction (). Commit (); Session.close ();}
4. Student.hbm.xml Change to:
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public "-//hibernate/hibernate mapping DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
hibernate--combined PRIMARY Key--xml