A tutorial on the creation and use of composite primary key mappings in the Java Hibernate framework _java

Source: Internet
Author: User
Tags commit rollback sessions

Composite primary key mappings need to use the <composite-id> tag in the mapping configuration file, which refers to specifying a class as the corresponding composite primary key, and its Name property needs to specify the attribute value defined in the class file and add <key-property to the label > Child labels.
Note: To use a composite map, you must place the composite primary key in a class, that is, compound primary key attributes and other attributes are divided into two classes, and the class of the composite primary key is implemented as an interface serializable, which is subordinate to java.io.
The primary key of a composite primary key is a composite of multiple columns, which corresponds to a fairly simple data table, as shown in the following diagram:

1. Class documents
here, take the table on the diagram as an example, with two field years and durations in the table as the primary key of the table, so the new classes are named Fiscalyearperiod and FISCALYEARPERIODPK, respectively. Where the FISCALYEARPERIODPK class encapsulates the primary key properties of the table, the Fiscalyearperiod class encapsulates other attributes, and the FISCALYEARPERIODPK class.
1.1 Fiscalyearperiod.java
the class encapsulates the basic attributes and encapsulates the FISCALYEARPERIODPK class as a property into the class and configures the corresponding mappings in the configuration file, as follows:

 package com.src.hibernate; 
 
Import Java.sql.Date; 
  public class Fiscalyearperiod {//Time primary key private FISCALYEARPERIODPK fiscalyearperiodpk; 
  Public FISCALYEARPERIODPK getfiscalyearperiodpk () {return fiscalyearperiodpk; } public void Setfiscalyearperiodpk (FISCALYEARPERIODPK fiscalyearperiodpk) {this.fiscalyearperiodpk = FiscalYearP 
  ERIODPK; 
  }//Start date private date begindate; 
  Public Date Getbegindate () {return begindate; 
  The public void Setbegindate (Date begindate) {this.begindate = begindate; 
  }//End date private date enddate; 
  Public Date Getenddate () {return enddate; 
  The public void Setenddate (Date enddate) {this.enddate = EndDate; 
  }//Phase time private String periodsts; 
  Public String getperiodsts () {return periodsts; 
  } public void Setperiodsts (String periodsts) {this.periodsts = periodsts; } 
} 

1.2 Fiscalyearperiodpk.java
encapsulates the primary key property, which is separated from the Fiscalyearperiod class, contains basic primary key properties, and implements interface serializable, which is to be mapped to a configuration file <composite-id> Label to specify the class, the code is as follows:

Package com.src.hibernate; 
 
Import java.io.Serializable; 
 
public class FISCALYEARPERIODPK implements Serializable { 
   
  //age 
  private int fiscalyear; 
  public int getfiscalyear () {return 
    fiscalyear; 
  } 
  public void setfiscalyear (int fiscalyear) { 
    this.fiscalyear = fiscalyear; 
  } 
 
  Duration 
  private int fiscalperiod; 
  public int Getfiscalperiod () {return 
    fiscalperiod; 
  } 
 
  public void setfiscalperiod (int fiscalperiod) { 
    this.fiscalperiod = fiscalperiod; 
  } 
   
} 

2. Configuration file
here's a question. Which one of the two classes needs to add a mapping file? Because the <composite-id> tag is used, you only need to add mappings for the Fiscalyearperiod class, add the corresponding composite primary key label to the mapping file, and add the corresponding primary key attribute to the tag, as follows:

<?xml version= "1.0"?> 
<! DOCTYPE hibernate-mapping public  
  "-//hibernate/hibernate mapping DTD 3.0//en" 
  "http:// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd "> 

drop table if exists t_fiscal_year_period_pk 
create table t_fiscal_year_period_pk (FiscalYear integer NOT NULL, FISCA Lperiod integer NOT NULL, begindate date, EndDate date, periodsts varchar (255), primary key (FiscalYear, Fiscalperiod)) 

The corresponding table structure is shown below:

3. Data operation
after the corresponding mapping file is configured, the corresponding data operation becomes very simple, starting from writing data, writing data to the database will write two classes to the database at the same time, so these two classes must be converted to transient state, So when you save, you need to first save the Fiscalyearperiod object to the database, and then it automatically associates the composite attribute and saves the information to the database.
3.1 Write operations
the Write action method is the same as the previous write method, you need to define two objects, and then save the corresponding object information to the database, the code is as follows:

public void TestSave1 () { 
  //declaring Session object sessions 
  Session=null; 
   
  try{ 
    //Get Session Object 
    session=hibernateutils.getsession (); 
    Open session 
    session.begintransaction (); 
    Create a composite object 
    fiscalyearperiodpk fiscalyearperiodpk=new fiscalyearperiodpk (); 
    Fiscalyearperiodpk.setfiscalperiod (2014); 
    Fiscalyearperiodpk.setfiscalyear (a); 
     
    Create Object 
    fiscalyearperiod fiscalyearperiod=new fiscalyearperiod (); 
    FISCALYEARPERIOD.SETFISCALYEARPERIODPK (FISCALYEARPERIODPK); 
     
    Session.save (fiscalyearperiod); 
    Submit Session 
    Session.gettransaction (). commit (); 
  catch (Exception e) { 
    e.printstacktrace (); 
    Session.gettransaction (). rollback (); 
  } finally{ 
    Hibernateutils.closesession (session); 
  } 
 

Execute the appropriate test method, and the resulting SQL statement is as follows:

Hibernate: insert into t_fiscal_year_period_pk (beginDate, endDate, periodSts, fiscalYear, fiscalPeriod) values (?, ?, ?, ?, ?) 
The corresponding database view:

3.2 Load Operation
the corresponding load method will be different from the previous one, because the primary key is a composite property in the table, so you need to create a class. When loading data, you need to create a primary key object, at which point the primary key is an object, and you need to assign a value to the object's properties to get the object, as follows:

public void TestLoad1 () { 
  //declaring Session object sessions 
  Session=null; 
   
  try{ 
    //Get Session Object 
    session=hibernateutils.getsession (); 
    Open session 
    session.begintransaction (); 
    Create a composite object 
    fiscalyearperiodpk fiscalyearperiodpk=new fiscalyearperiodpk (); 
    Fiscalyearperiodpk.setfiscalperiod (2014); 
    Fiscalyearperiodpk.setfiscalyear (a); 
     
    Fiscalyearperiod fiscalyearperiod= (fiscalyearperiod) session.load (FISCALYEARPERIOD.CLASS,FISCALYEARPERIODPK); 
    System.out.println ("Start Date:" +fiscalyearperiod.getbegindate ());  
    Submit Session 
    Session.gettransaction (). commit (); 
  catch (Exception e) { 
    e.printstacktrace (); 
    Session.gettransaction (). rollback (); 
  } finally{ 
    Hibernateutils.closesession (session); 
  } 
 

The resulting results are as follows:

Hibernate:select fiscalyear0_.fiscalyear as fiscalyear0_0_, fiscalyear0_.fiscalperiod as fiscalPe2_0_0_, fiscalyear0_ . begindate as begindate0_0_, fiscalyear0_.enddate as enddate0_0_, fiscalyear0_.periodsts as periodSts0_0_ from T_fiscal_ YEAR_PERIOD_PK fiscalyear0_ where fiscalyear0_.fiscalyear=? and fiscalyear0_.fiscalperiod=? 
Start Date: 2013-10-12 

4. Comprehensive example
a Department table (HIBERNATE_DEPT_COMPOSITEPK) of a large company consisting of fields (area), Department name (name), number of units (Empcount), build time (birthday), etc. We use the region and department name to do the joint primary key:
4.1 Target class: Department.java

 public class Department {/** Abstract the primary key association attribute into a separate class///private String area; 
 private String name; 
 /** the primary key class object as a member variable */private DEPARTMENTPK DEPARTMENTPK; 
 private int empcount; 

Private Date birthday; 
Public String Getarea () {//return area; 
////public void Setarea (String area) {//This.area = area; 
////Public String GetName () {//return name; 
////public void SetName (String name) {//this.name = name; 
 public int Getempcount () {return empcount; 
 The public void Setempcount (int empcount) {this.empcount = Empcount; 
 Public Date Getbirthday () {return birthday; 
 The public void Setbirthday (Date birthday) {this.birthday = birthday; 
 Public DEPARTMENTPK GETDEPARTMENTPK () {return DEPARTMENTPK; 
 public void Setdepartmentpk (DEPARTMENTPK departmentpk) {this.departmentpk = DEPARTMENTPK; } 

}

4.2 Primary Key classes: Departmentpk.java

public class DEPARTMENTPK implements Serializable {private static final long serialversionuid = -288002855915204255l; 
 Private String area; 
 private String name; 
  /** * Overlay Hashcode method (judged by area and name)//@Override public int hashcode () {final int prime = 31; 
  int result = 1; 
  result = Prime * result + ((area = = null) 0:area.hashcode ()); 
  result = Prime * result + ((name = = null) 0:name.hashcode ()); 
 return result; /** * Overwrite equals (judged by area and name)/@Override public boolean equals (Object obj) {if (this = obj) retur 
  n true; 
  if (obj = null) return false; 
  if (GetClass ()!= Obj.getclass ()) return false; 
  Final DEPARTMENTPK other = (DEPARTMENTPK) obj; 
  if (area = = null) {if (Other.area!= null) return false; 
  else if (!area.equals (Other.area)) return false; 
  if (name = = null) {if (other.name!= null) return false; 
  else if (!name.equals (Other.name)) return false; return true; 
 Public String Getarea () {return area; 
 public void Setarea (String area) {This.area = area; 
 Public String GetName () {return name; 
 public void SetName (String name) {this.name = name;

 } 
}

4.3 Mapping file Department.hbm.xml

<?xml version= "1.0"?> 
<! DOCTYPE hibernate-mapping public  
 "-//hibernate/hibernate mapping DTD 3.0//en" 
 "http:// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd "> 
 
 

4.4 Hibernate configuration file Hibernate.cfg.xml

<?xml version= ' 1.0 ' encoding= ' UTF-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hi                   Bernate.sourceforge.net/hibernate-configuration-3.0.dtd "> <!--generated by MyEclipse hibernate Tools. -->  

4.5 Test class: Departmenttest.java

public class Departmenttest extends TestCase {/** * Test insert data */public void Save () {Sessions session = Hibern 
  Ateutils.getsession (); 
  Transaction t = session.begintransaction (); 
   try {Department dept = new Department (); 
   /** generate primary Key Object */DEPARTMENTPK DEPTPK = new DEPARTMENTPK (); 
   Deptpk.setarea ("Beijing"); 
   Deptpk.setname ("Research and Development department"); 

   DEPT.SETDEPARTMENTPK (DEPTPK); 
   Dept.setempcount (100); 

   Dept.setbirthday (New Date ()); 
   Session.save (dept); 
  T.commit (); 
   catch (Hibernateexception e) {e.printstacktrace (); 
  T.rollback (); 
  finally {hibernateutils.closesession (session); 
  }/** * Test load data/public void load () {Sessions session = Hibernateutils.getsession (); 
  Transaction t = session.begintransaction (); 
   try {/** Generate primary Key Object */DEPARTMENTPK DEPTPK = new DEPARTMENTPK (); 
   Deptpk.setarea ("Beijing"); 

   Deptpk.setname ("Research and Development department"); 
   Department dept= (Department) session.load (Department.class, DEPTPK); System.out.prIntln (DEPT.GETDEPARTMENTPK (). Getarea () + "," +DEPT.GETDEPARTMENTPK (). GetName () + "," +dept.getempcount () + "," + 
  Dept.getbirthday ()); 
   catch (Hibernateexception e) {e.printstacktrace (); 
  T.rollback (); 
  finally {hibernateutils.closesession (session); 
  }/** * Test modified data/public void Update () {Session session = Hibernateutils.getsession (); 
  Transaction t = session.begintransaction (); 
   try {/** Generate primary Key Object */DEPARTMENTPK DEPTPK = new DEPARTMENTPK (); 
   Deptpk.setarea ("Beijing"); 

   Deptpk.setname ("Research and Development department"); 
   Department emp= (Department) session.load (Department.class, DEPTPK); System.out.println (EMP.GETDEPARTMENTPK (). Getarea () + "," +EMP.GETDEPARTMENTPK (). GetName () + ", +emp.getempcount () +" 
   , "+emp.getbirthday ()); 
   Emp.setempcount (100); 
    
   Session.saveorupdate (EMP); 
   /** generate primary Key Object */DEPARTMENTPK deptPK2 = new DEPARTMENTPK (); 
   Deptpk2.setarea ("Beijing"); 
   Deptpk2.setname ("Research and Development department"); Department dept= (Department) session.load (Department.class, DEPTPK2); System.out.println (DEPT.GETDEPARTMENTPK (). Getarea () + "," +DEPT.GETDEPARTMENTPK (). GetName () + "," +dept.getempcount ( 
   ) + "," +dept.getbirthday ()); 
  T.commit (); 
   catch (Hibernateexception e) {e.printstacktrace (); 
  T.rollback (); 
  finally {hibernateutils.closesession (session); 
  }/** * Test Delete data */public void Delete () {Session session = Hibernateutils.getsession (); 
  Transaction t = session.begintransaction (); 
   try {/** Generate primary Key Object */DEPARTMENTPK DEPTPK = new DEPARTMENTPK (); 
   Deptpk.setarea ("Beijing"); 
    
   Deptpk.setname ("Research and Development department"); 
   Department dept= (Department) session.load (Department.class, DEPTPK); 
   Session.delete (dept); 
  T.commit (); 
   catch (Hibernateexception e) {e.printstacktrace (); 
  T.rollback (); 
  finally {hibernateutils.closesession (session);
 } 
 } 
}

Related Article

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.