Hibernate annotation way to implement compound primary key

Source: Internet
Author: User

Sometimes an entity's primary key may be multiple, such as the "Customereo" entity that was previously used, to find the specified entity by name and email, and it is considered the same entity object only if the value of name and email is exactly the same. To configure such a composite primary key, the steps are shown below.

(1) Write a composite primary key class CUSTOMERPK, the code is as follows.

Customerpk.java

import java.io.Serializable;





public class CUSTOMERPK implements Serializable {





public customerpk () {





          }





public customerpk (string name, string email) {


this.name = name;


this.email = email;


          }





private String Email;





public String Getemail () {


return email;


          }





public void Setemail (String email) {


this.email = email;


          }





private String name;





public String GetName () {


return name;


          }





public void SetName (String name) {


this.name = name;


          }





@Override


public int hashcode () {


final int PRIME = 31;


int result = 1;


result = PRIME * result + (email = null)? 0:email. Hashcode ());


result = PRIME * result + ((name = = null)? 0:name.hashcode ());


return result;


          }





@Override


public boolean equals (Object obj) {


if (this = = obj)


return true;


if (obj = null)


return false;


if (getclass ()!= obj.getclass ())


return false;


final CUSTOMERPK other = (CUSTOMERPK) obj;


if (email = = NULL) {


if (other.email!= null)


return false;


} else if (!email. Equals (Other.email))


return false;


if (name = = null) {


if (other.name!= null)


return false;


} else if (!name.equals (other.name))


return false;


return true;


          }





}

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.