Eclipse quickly hibernate--5. Component Mappings

Source: Internet
Author: User
Tags final generator insert key log sql string thread
This article is mainly about the component (Component) mappings in Hibernate, which can be referenced in chapter 7th of the Hibernate official documentation.  As for the environment settings, you can refer to the previous articles in this series.  1. Create Project ·   Create a new Java project: Componentmapping, and note that creating a separate source folder and output folder is selected, adding the user library: Hibernate.  2. Writing class documents · Create a new class, package Name: Javamxj.hibernate.component, class name: Person.
Person.java

* * Hibernate-component (Component) mapping * creation Date 2005-4-10 * @author javamxj (share java Fun) * @link blog:htpp://javamxj.mblogger.cn * H tpp://blog.csdn.net/javamxj/*/package javamxj.hibernate.component;/** * @hibernate. class */public class Person { Private Long id;private String username;private address address;/** * @hibernate. ID *generator-class= "Hilo" * Unsaved-value= "null" */public Long getId () {return ID;} public void SetId (Long id) {this.id = ID;} /** * @hibernate. Property * length= ' * unique= "true" * not-null= "true" */public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} /** * @hibernate. Component */public Address getaddress () {return address;} public void setaddress [address] {this.address = address;}}
·  The person class calls the address class, noting the "@hibernate. Component" tag on the "GetAddress ()" method. · The address class contains only "@hibernate. Property" tags and does not map them independently to a single table.
Address.java

Package Javamxj.hibernate.component;public class Address {private string country;private string City;private string Street;private string Zipcode;public Address () {}public address (string country, String city, String Street, String ZipCode {super (); this.country = country;this.city = City;this.street = Street;this.zipcode = ZipCode;} /** * @hibernate. Property * length = "a" */public String getcity () {return city;} public void Setcity (String city) {this.city = city;} /** * @hibernate. Property * length = "a" */public String Getcountry () {return country;} public void Setcountry (String country) {this.country = country;} /** * @hibernate. Property * length = ' 6 ' */public String Getzipcode () {return zipCode;} public void Setzipcode (String number) {this.zipcode = number;} /** * @hibernate. Property * length = "a" */public String Getstreet () {return street;} public void Setstreet (String street) {this.street = Street;} Public String toString () {return ("live in" + Country + city+ "City" + street+ "district" + "\n\t Zip Code:" + ZipCode);}
3. Run the Task · Copy the Eclipse Quick Start hibernate--4.  Inheritance mapping (1) in the article Build.xml to the project directory. · Double-click the "GENERATE-HBM" task, you will find in the package more than a Animal.hbm.xml file, in the SRC directory will be more than a hibernate.cfg.xml file, if not, press the F5 key to refresh.
Person.hbm.xml

<?xml version= "1.0" encoding= "GBK"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 2.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-2.0.dtd ">· Run the MySQL server, and then double-click the "Schemaexport" task, which produces a "schema-export.sql" file under the project root. Schema-export.sql
drop table if exists Persondrop table if exists hibernate_unique_keycreate table person (ID bigint not NULL, username var Char NOT NULL unique, city varchar (in), Country varchar (), ZipCode varchar (6), street varchar (), primary key (ID)) CREATE TABLE Hibernate_unique_key (Next_hi integer) insert into Hibernate_unique_key values (0)
· When you switch to a database, you will find that you have automatically generated the data table person 5.  Test program this time different from the previous several examples, this time to implement a Hibernateutil helper class, to manage Hibernate session, so that the test class code is relatively simple, you can refer to the Hibernate Official document 1th chapter. · Create a new class, package Name: Javamxj.hibernate.util, class name: Hibernateutil, code as follows:
Hibernateutil.java

Package Javamxj.hibernate.util;import Org.apache.commons.logging.log;import Org.apache.commons.logging.LogFactory ; Import Net.sf.hibernate.hibernateexception;import Net.sf.hibernate.session;import Net.sf.hibernate.sessionfactory;import Net.sf.hibernate.transaction;import net.sf.hibernate.cfg.Configuration; public class Hibernateutil {private static log log = Logfactory.getlog (hibernateutil.class);p rivate static Sessionfactory sessionfactory;private static final ThreadLocal threadsession = new ThreadLocal ();p rivate static final Thr Eadlocal threadtransaction = new ThreadLocal ();p ublic static Sessionfactory getsessionfactory () {if (sessionfactory = = Nu ll) {try {//Create the sessionfactorysessionfactory = new Configuration (). Configure (). Buildsessionfactory ();} catch ( Hibernateexception ex) {ex.printstacktrace (); throw new RuntimeException ("Configuration problem:" + ex.getmessage (), ex );}} return sessionfactory;} public static sessions Currentsession () throws Hibernateexception {session S = (Session) Threadsession.get ()//Open A new session, if this Thread has none yetif (s = = null) {s = Getsessionfactory (). Opense Ssion (); Log.debug ("# # #Opening new session for this thread: + s); Threadsession.set (s);} else {log.debug ("# # #Session was existed:" + s);} return s;} public static void CloseSession () throws Hibernateexception {Sessions S = (session) Threadsession.get (); threadsession.set (null); if (s!= null) {Log.debug ("# # #Closing Session of ' this thread." + s); S.close ()}} public static void BeginTransaction () throws hibernateexception {Transaction tx = (Transaction) threadtransaction.get (); try {if (tx = = null) {tx = Currentsession (). BeginTransaction (); Log.debug ("# # #Starting New database transaction in this THR EAD: "+ tx); Threadtransaction.set (TX);} else {log.debug ("# # #Tx was existed:" + Tx);}} catch (Hibernateexception ex) {throw ex;}} public static void CommitTransaction () throws hibernateexception {Transaction tx = (Transaction) threadtransaction.get () ; try {if (tx!= null &&!TX. wascommitted () &&!tx.wasrolledback ()) {Log.debug ("# # #Committing database transaction of this thread."); Tx.commit ();} Threadtransaction.set (null);} catch (Hibernateexception ex) {rollbacktransaction (); throw ex;}} public static void RollbackTransaction () throws hibernateexception {Transaction tx = (Transaction) threadtransaction.get (); try {threadtransaction.set (null); if (TX!= null &&!tx.wascommitted () &&!tx.wasrolledback ()) { Log.debug ("# # #Tyring to rollback database transaction The this thread."); Tx.rollback ();} catch (Hibernateexception ex) {throw ex;} finally {closesession ();}}}
· OK, then create a new Componentdemo.java class under the package javamxj.hibernate.component.
Componentdemo.java

Package Javamxj.hibernate.component;import Java.util.iterator;import Java.util.list;import Javamxj.hibernate.util.hibernateutil;import Net.sf.hibernate.hibernateexception;import net.sf.hibernate.Session; public class Componentdemo {public static void main (string[] args) {try {new Componentdemo ();} catch (Hibernateexception h e) {he.printstacktrace ();}} Public Componentdemo () throws Hibernateexception {session sess = Hibernateutil.currentsession (); Person p = new person ();p. setaddress ("China", "Shanghai", "Putuo", "200055");p. Setusername ("Javamxj"); Sess.save (p);p = New Person ();p. setaddress ("China", "Beijing", "Haidian", "100086");p. Setusername ("John"); Sess.save (P); List animals = sess.find ("from" + Person.class.getName ()), for (Iterator it = Animals.iterator (); It.hasnext ();) {Person person = (person) it.next (); System.out.println (Person.getusername () + ":" + person.getaddress ());} Hibernateutil.closesession ();}
·  Running this class, the console output is as follows: ·  At the same time, the data table produces the following data: · The final project structure is as follows:

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.