Hibernate Manytoone Mappings Many-to-one association mappings
steps to use Hibernate framework:
1. Create Hibernate configuration file (Hibernate.cfg.xml)
2. Create a persistence class, that is, the class whose instance needs to be saved to the database (Employee.java)
3. Create object-relational mapping file (Employee.hbm.xml)
4. Write code to access the database through the Hibernate API
Example: multiple employees correspond to one address.
First, create the Hibernate.cfg.xml configuration file:
Note that the database name, user name, and password are filled in correctly.
<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-configuration SYSTEM "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >< Hibernate-configuration><session-factory><property name= "Hibernate.dialect" > Org.hibernate.dialect.mysqldialect</property><property name= "Hibernate.connection.driver_class" > com.mysql.jdbc.driver</property><!--assume Testone is the database name--><property name= " Hibernate.connection.url ">jdbc:mysql://localhost/testmany2one</property><property name=" Hibernate.connection.username ">root</property><property name=" Hibernate.connection.password "> Root</property><property name= "Hibernate.show_sql" >true</property><!--List of XML mapping Files--><mapping resource= "Resource/employee.hbm.xml"/></session-factory></ Hibernate-configuration>
Second, create the persistence class, that is, the classes whose instances need to be saved to the database (Employee.java, Address.java)
Employee.java
package com.jiangge.hblearn;/** * @author Jiangge */public class employee{private int id;private string Firstname;private string L astname;private int salary;private Address Address;public employee () {}public employee (string firstName, String lastName , int salary,address Address) {this.firstname = Firstname;this.lastname = Lastname;this.salary = Salary;this.address = add ress;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getfirstname () {return firstName;} public void Setfirstname (String firstName) {this.firstname = FirstName;} Public String Getlastname () {return lastName;} public void Setlastname (String lastName) {this.lastname = LastName;} public int getsalary () {return salary;} public void setsalary (int salary) {this.salary = salary;} Public Address getaddress () {return address;} public void setaddress (address address) {this.address = address;}}
Address.java
Package com.jiangge.hblearn;/** * @author Shijiangge * @version 2014-7-4 a.m. 11:05:39 * */public class address{private I NT Id;private string Street;private string city;private string State;private string Zipcode;public Address () {}public Addr ESS (String Street, String city, String state, String zipcode) {This.street = Street;this.city = City;this.state = State;thi S.zipcode = ZipCode;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getstreet () {return street;} public void Setstreet (String street) {this.street = Street;} Public String getcity () {return city;} public void Setcity (String city) {this.city = city;} Public String GetState () {return state;} public void SetState (String state) {this.state = state;} Public String Getzipcode () {return zipcode;} public void Setzipcode (String zipcode) {this.zipcode = ZipCode;}}
to create a table in MySQL:
CREATE TABLE EMPLOYEE ( ID INT not NULL auto_increment, first_name VARCHAR () default NULL, last_name VARCHAR () default NULL, salary int default NULL, address int not null, PRIMARY KEY (id));
CREATE TABLE ADDRESS ( ID INT not NULL auto_increment, street_name VARCHAR (+) default NULL, city_name VAR CHAR (max) default NULL, state_name varchar (+) default NULL, zipcode varchar (TEN) default NULL, PRIMARY KEY (ID));
Iii. Creating an Object-relational mapping file (Employee.hbm.xml)
<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd "><!--Hibernate Many-to-one Association: Many employees can correspond to one address. Beginner Programmer Handwriting Employee.hbm.xml mapping files, while advanced programmers use Xdoclet, Middlegen and Andromda these techniques to automatically generate mapping files. The META tag is optional and is used to describe the class. Hibernate's primary key generation strategy: "Identity" takes the primary key generation mechanism provided by the database. such as DB2, SQL Server, MySQL in the primary key generation mechanism. "Native" is determined by Hibernate using the identity, Hilo, sequence as the primary key generation method according to the database used. -->
Iv. Writing code to access the database through the Hibernate API
Package Test;import Java.util.*;import Org.hibernate.hibernateexception;import org.hibernate.session;import Org.hibernate.transaction;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;import Com.jiangge.hblearn.address;import com.jiangge.hblearn.employee;/** * Test class: crud operation * @author Jiangge * */public class Manageemployee{private static sessionfactory factory;public static void Main (string[] args) {try{factory = new Configuration (). Configure (). Buildsessionfactory ();} catch (Throwable ex) {System.err.println ("Failed to create Sessionfactory object." + ex); throw new Exceptionininitializererror (ex);} Manageemployee ME = new Manageemployee ();/* Let us have one address object */address address = me.addaddress ("Kondapur", " Hyderabad "," AP "," 532 ");/* ADD employee records in the database */integer empID1 = Me.addemployee (" Manoj "," Kumar ", 4000, address); ("Manoj", "Kumar", 4000, address);/* ADD Another employee record in the database */integer empID2 = Me.addemployee ("DiLip "," Kumar ", +, address);//(" Dilip "," Kumar "," n ", address);/* List down all the Employees */me.listemployees ();/* U Pdate Employee's salary records */me.updateemployee (empID1, Sat);/* Delete an employee from the database */me.deleteemplo Yee (empID2);/* List down all the Employees */me.listemployees ();} /* Method to add a address record in the database */public address addaddress (String Street, String city, string state, S Tring ZipCode) {Session session = Factory.opensession (); Transaction tx = Null;integer addressid = null; Address address = NULL;TRY{TX = Session.begintransaction (); address = new address (street, city, State, zipcode); addressid = (Integer) Session.save (address); Tx.commit ();} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} Finally{session.close ();} return address;} /* Method to add a employee record in the database */public Integer addemployee (String fname, string lname, int salary,ad Dress Address) {Session session = Factory.opensession (); TRansaction tx = Null;integer EmployeeID = NULL;TRY{TX = Session.begintransaction (); Employee Employee = new Employee (fname, lname, salary, address), EmployeeID = (Integer) session.save (employee); Tx.commit ( );} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} finally{session.close ();} return EmployeeID;} /* Method to list all the employees detail */public void Listemployees () {Session session = Factory.opensession (); Transaction tx = NULL;TRY{TX = Session.begintransaction (); List employees = Session.createquery ("from Employee"). List (), for (Iterator Iterator = Employees.iterator (); Iterator.hasnext ();) {Employee employee = (employee) iterator.next (); System.out.print ("First Name:" + employee.getfirstname ()); System.out.print ("Last Name:" + employee.getlastname ()); System.out.println ("Salary:" + employee.getsalary ()); Address add = employee.getaddress (); System.out.println ("Address"); System.out.println ("\tstreet:" + add.getstreet ()); System.out.println ("\tcity:"+ add.getcity ()); System.out.println ("\tstate:" + add.getstate ()); System.out.println ("\tzipcode:" + add.getzipcode ());} Tx.commit ();} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} finally{session.close ();}} /* Method to update salary-an employee */public void UpdateEmployee (Integer EmployeeID, int salary) {Session session = Factory.opensession (); Transaction tx = NULL;TRY{TX = Session.begintransaction (); Employee employee = (employee) session.get (Employee.class,employeeid); employee.setsalary (salary); Session.update ( Employee); Tx.commit ();} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} finally{session.close ();}} /* Method to delete a employee from the records */public void Deleteemployee (Integer EmployeeID) {Session session = Factor Y.opensession (); Transaction tx = NULL;TRY{TX = Session.begintransaction (); Employee employee = (employee) session.get (Employee.class, EmployeeID); Session.delete (employee); Tx.commit ();} catch (HibeRnateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} finally{session.close ();}}}
V. Results of Operation:Mysql> SELECT * from employee;+----+------------+-----------+--------+---------+| ID | first_name | last_name | Salary | Address |+----+------------+-----------+--------+---------+| 1 | Manoj | Kumar | | 1 |+----+------------+-----------+--------+---------+1 row in setmysql> select * from address;+----+-------------+- ----------+------------+---------+| ID | Street_name | City_name | State_name | ZipCode |+----+-------------+-----------+------------+---------+| 1 | Kondapur | Hyderabad | AP | 532
Log4j:warn No Appenders could is found for logger (org.hibernate.cfg.Environment). Log4j:warn Please initialize the log4j s Ystem properly. Hibernate:insert into ADDRESS (Street_name, City_name, State_name, ZipCode) VALUES (?,?,?,?) Hibernate:insert into EMPLOYEE (first_name, last_name, salary, address) VALUES (?,?,?,?) Hibernate:insert into EMPLOYEE (first_name, last_name, salary, address) VALUES (?,?,?,?) Hibernate:select employee0_.id as id0_, employee0_.first_name as first2_0_, employee0_.last_name as last3_0_, employee0_ . Salary as salary0_, employee0_.address as address0_ from EMPLOYEE Employee0_first Name:manoj last Name:kumar Salary: 4000Address Hibernate:select address0_.id as id1_0_, address0_.street_name as street2_1_0_, address0_.city_name as City3 _1_0_, Address0_.state_name as state4_1_0_, Address0_.zipcode as zipcode1_0_ from ADDRESS address0_ where address0_.id=? Street:kondapurcity:hyderabadstate:apzipcode:532first Name:dilip last Name:kumar salary:3000Address Street:kondapurcity:hyderabadstate:apzipcode:532hibernate:select employee0_.id as id0_0_, employee0_. First_Name as first2_0_0_, employee0_.last_name as last3_0_0_, employee0_.salary as salary0_0_, employee0_.address as add ress0_0_ from EMPLOYEE employee0_ where employee0_.id=? Hibernate:update EMPLOYEE set first_name=, last_name=?, salary=?, address=? where id=? Hibernate:select employee0_.id as id0_0_, employee0_.first_name as first2_0_0_, employee0_.last_name as last3_0_0_, Empl Oyee0_.salary as salary0_0_, employee0_.address as address0_0_ from EMPLOYEE employee0_ where employee0_.id=? Hibernate:delete from EMPLOYEE where id=? Hibernate:select employee0_.id as id0_, employee0_.first_name as first2_0_, employee0_.last_name as last3_0_, employee0_ . Salary as salary0_, employee0_.address as address0_ from EMPLOYEE Employee0_first Name:manoj last Name:kumar Salary: 5000Address Hibernate:select address0_.id as id1_0_, address0_.street_name as street2_1_0_, Address0_.ciTy_name as city3_1_0_, address0_.state_name as state4_1_0_, Address0_.zipcode as zipcode1_0_ from ADDRESS address0_ where Address0_.id=? street:kondapurcity:hyderabadstate:apzipcode:532
Reference Documents:Http://www.tutorialspoint.com/hibernate/hibernate_many_to_one_mapping.htm