Springdata JPA Composite PRIMARY key

Source: Internet
Author: User
Tags findone

The previous blog briefly introduced the Springdata JPA implementation of a simple crud, pagination and multi-conditional sorting, where the primary key type is a long, sometimes we will encounter the primary key is not a, composite primary key, after investigation as follows. Identify a person, not only according to his name to determine, because there will be duplicate names, now we assume that the name, social security number to determine the only person.

Composite PRIMARY key: A table exists multiple fields together to form a primary key, and the combination of multiple fields cannot be repeated, but a single one can be repeated.

Example: the name and the province certificate number together form the primary key

One,Spring Data JPA Composite PRIMARY key

1.1. Write a composite primary key class: Peoplekey

@Embeddablepublic class Peoplekey implements Serializable  {@Column (name = "name") private String name; @Column (name = "Idcardno") private string idcardno;//omit Setter,getter method @overridepublic string toString () {return ' Peoplekey [name= ' + Name + ", idcardno=" + Idcardno + "]";}}

Attention:

1) Implement Serializable the interface (otherwise will error, errors will be displayed directly);

2) on the class of the composite primary key, use the annotation @embeddable

3) There is a default public parameterless construction method (in my case, I did not add a method to construct a parameter, so the default constructor method is used)

If you have a constructor in the entity class, then there must be a method of non-parametric construction, otherwise it will be error when running

Org.hibernate.InstantiationException:No default constructor for entity:  : Com.my.model.People

This is caused by the absence of a default constructor method, so add the default parameterless constructor to the entity class.

4) Overrides equals and hashCode methods. The Equals method is used to determine whether two objects are the same, and Entitymanger is judged by the return value of equals when searching for an entity through the Find method. The Hashcode method returns the hash code of the current object (I verify that entitymanger, not rewriting is fine.) );

1.2. Write the entity class: People

Package Com.my.model;import javax.persistence.*; @Entity @table (name = "People")//@IdClass (Peoplekey.class) public Class people extends peoplekey{//composite primary key to use this annotation @embeddedidprivate peoplekey ID; @Column (name = "Age") private int age; @Colu MN (name = "Address") private string address;//omit Setter,getter method @overridepublic string toString () {return ' people [id= ' + I D + ", age=" + Age + ", address=" + address+ "]";}}

1.3 Test:

@Servicepublic class Peopleservice {@Resourceprivate peoplerepository peoplerepository;public people FindOne () { Peoplekey Peoplekey = new Peoplekey ();p eoplekey.setname ("Zhang San");p Eoplekey.setidcardno ("340123"); People people = Peoplerepository.findone (Peoplekey); return people;}}

Output from the console:

People [Id=peoplekey [Name= Zhang San, idcardno=340123], age=3, address= decomposition points]

Second, the use of @idclass to annotate the composite primary key

The process is similar to @embeddable, which is directly attached to the example.

@Entity @table (name = "People") @IdClass (Peoplekey.class) public class people  implements Serializable {//@ Embeddedid//private peoplekey ID; @Id @column (name = "name") private String name; @Id @column (name = "Idcardno") private string Idcardno; @Column (name = "Age") private int age; @Column (name = "Address") private String address;

public class Peoplekey implements Serializable  {//@Id//@Column (name = "name") Private String name;//@Id//@Column ( Name = "Idcardno") private String Idcardno;}

Use this method of my reference blog has a, write more detailed, but feel this method is not good, itself already in Peoplekey the primary key to encapsulate, but in the entity class people also want to add compound primary key to join, not brief, adopt the first method, it is very simple, It also embodies the idea of Java class encapsulation.

Third, the verification of Entitymanager, directly on the code

Package Com.my.model;import Java.io.serializable;import Javax.persistence.column;import Javax.persistence.embeddable;import Javax.persistence.entity;import javax.persistence.id;//@Embeddablepublic Class Peoplekey implements Serializable  {//@Id//@Column (name = "name") Private String name;//@Id//@Column (name = " Idcardno ") private string Idcardno;public string GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getidcardno () {return idcardno;} public void Setidcardno (String idcardno) {this.idcardno = Idcardno;} @Overridepublic String toString () {return "Peoplekey [name=" + name + ", idcardno=" + Idcardno + "]";}}

  

Package Com.my.model;import Java.io.serializable;import javax.persistence.*; @Entity @table (name = "People") @IdClass ( Peoplekey.class) public class People {//@EmbeddedId//private peoplekey ID; @Column (name = ' age ') private int age; @Column ( Name = "Address") Private String address;//public Peoplekey getId () {//return id;//}////public void setId (Peoplekey ID) {// This.id = id;//}//@Id @column (name = "name") private string name; @Id @column (name = "Idcardno") private string Idcardno; Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getidcardno () {return idcardno;} public void Setidcardno (String idcardno) {this.idcardno = Idcardno;} public int getage () {return age;} Public people () {super ();} public void Setage (int.) {this.age = age;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} @Overridepublic String toString () {return "people [age=" + Age + ", address=" + address + ", name=" + name+ ", IDcardno= "+ Idcardno +"] ";}} 

Test:

  @RequestMapping (value = "/useentitymanager") public void Finduseentitymanager () throws Exception    {Peoplekey Peoplekey = new Peoplekey ();p eoplekey.setname ("Zhang San");p Eoplekey.setidcardno ("340123");         People people = Entitymanager.find (People.class,peoplekey);         System.out.println (People.tostring ());    }

Results:

People [Age=3, address= decomposition points, Name= Zhang San, idcardno=340123]

  

Reference blog:

1, https://www.cnblogs.com/linjiqin/archive/2011/03/09/1978680.html

2, http://blog.csdn.net/qq_35056292/article/details/77892012

Springdata JPA Composite PRIMARY key

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.