hibernate--combined PRIMARY Key--xml

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.