Eclipse Quick Hibernate - 5. Component Mapping

xiaoxiao2021-03-05  22

This article is primarily to be a component mapped in Hibernate, and you can refer to Chapter 7 of Hibernate official documentation. As for environmental settings, you can refer to the previous article.

Create a project

· New Java project: ComponentMapping, pay attention to "Create a separate source folder and output folder" while adding "user library": hibernate.

2. Write a class file

· Create a category, package name: javamxj.hibernate.component, class name: Person.

Person.java

/ *

* Hibernate - Component mapping

* Create a date 2005-4-10

* @author javamxj (sharing java happiness)

* @Link Blog: htpp: //javamxj.mblogger.cn

* htpp: //blog.9cbs.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 = "15"

* unique = "true"

* not-null = "true"

* /

Public string getUsername () {return username;}

Public void setusername (string username) {this.username = usrname;}

/ **

* @ hibernate.component

* /

Public Address getaddress () {return address;}

Public void setaddress (address address) {this.address = address;}

}

• The Person class calls the Address class, pay attention to the "@ hibernate.component" tag on the "GetDress ()" method.

• The Address class only contains some "@ hibernate.property" tags, and does not map its independent map into a 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 = "12"

* /

PUBLIC STRING GETCITY () {Return City;}

Public void setcity (string city) {this.city = city;}

/ **

* @ hibernate.property

* Length = "12"

* /

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 = "12"

* /

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 Postal Code:" Zipcode);

}

}

3. Run the task

· Copy "

Eclipse quickly rapidly hibernate - 4. Inherited the build.xml in the article (1) "in the project directory.

· Double-click the "Generate-HBM" task, will find more animal.hbm.xml files in the package, there will be more hibernate.cfg.xml files in the src directory. If not, press the F5 button to refresh.

Person.hbm.xml

"- // Hibernate / Hibernate mapping DTD 2.0 // en"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

>

Name = "javamxj.hibernate.component.Person"

Dynamic-update = "false"

Dynamic-insert = "false"

SELECT-Before-update = "false"

Optimistic-Lock = "Version"

>

Name = "id"

COLUMN = "ID"

TYPE = "java.lang.long" Unsaved-value = "null"

>

To Add Non xdoclet generator parameters, Create a file named

Hibernate-generator-params-person.xml

Containing the additional parameters and place it in your merge dir.

->

Name = "username"

TYPE = "java.lang.string"

Update = "true"

INSERT = "True"

Access = "Property"

Column = "username"

Length = "15"

NOT-NULL = "True"

Unique = "True"

/>

Name = "Address"

Class = "javamxj.hibernate.component.address"

>

Name = "city"

TYPE = "java.lang.string"

Update = "true"

INSERT = "True"

Access = "Property"

COLUMN = "city"

LENGTH = "12"

/>

Name = "country"

TYPE = "java.lang.string"

Update = "true"

INSERT = "True"

Access = "Property"

Column = "country"

LENGTH = "12"

/>

Name = "zipcode"

TYPE = "java.lang.string"

Update = "true"

INSERT = "True"

Access = "Property"

Column = "zipcode"

Length = "6"

/>

Name = "street"

TYPE = "java.lang.string"

Update = "true"

INSERT = "True"

Access = "Property"

COLUMN = "street"

LENGTH = "12"

/>

To Add Non XDoclet Property Mappings, Create A File Named

Hibernate-Properties-Person.xml

Containing The Additional Properties and Place It in Your Merge Dir .-->

· Run the MySQL server, then double-click the "SchemaExport" task, which will generate a "schema-export.sql" file in the project root directory.

Schema-export.sql

Drop Table if EXISTS PERSON

DROP TABLE IF EXISTS HIBERNATE_UNIQUE_KEY

CREATE TABLE PERSON

ID Bigint NOT NULL,

Username varchar (15) Not null unique,

City varchar (12),

Country varchar (12),

Zipcode Varchar (6),

Street varchar (12),

Primary Key (ID)

)

Create Table Hibernate_unique_Key

Next_hi integer

)

INSERT INTO Hibernate_unique_Key Values ​​(0)

· Switch to the database, it will find that the data table is automatically generated.

5. Test procedure

● This time is different from the previous example. This time you enable a hibernateutil assisted class to manage Hibernate's session. This test class is relatively simple, you can refer to Chapter 1 of Hibernate official documentation.

· 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.hibActory;

Import net.sf.hibernate.transaction;

Import Net.sf.hibiBernate.cfg.configuration;

Public class hibernateutil {

Private static log log = logfactory.getlog (HibernateUtil.class);

PRIVATE STATIC sessionFactory sessionFactory;

Private static final threadlocal threadsession = new threeReadlocal ();

Private static final threadlocal threadtransaction = new threadlocal ();

Public static sessionFactory getsessionFactory () {

IF (sessionFactory == NULL) {

Try {

// Create the sessionFactory

SessionFactory = new configuration (). configure ()

.BUILDSessionFactory ();

} catch (hibernateException ex) {ex.printstacktrace ();

Throw New RuntimeException ("Configuration Problem:"

ex.getMessage (), EX);

}

}

Return sessionFactory;

}

Public static session currentsession () throws hibernateException {

SESSION S = (session) threadsssion.get ();

// Open a new session, if this thread HAS NONE YET

IF (s == NULL) {

S = getsessionFactory (). OpenSession ();

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 {

SESSION S = (session) threadsssion.get ();

Threadsession.Set (null);

IF (s! = null) {

Log.debug ("### closing session of this thread." s);

s.close ();

}

}

Public static void based begentransaction () throws hibernateException {

THREADTRANSACTION.GET ();

Try {

IF (tx == null) {

TX = currentsession (). Begintransaction ();

Log.debug ("### Starting New Database Transaction In this thread:" TX);

ThreadTransaction.Set (TX);

} else {

Log.debug ("### TX WAS EXISTED:" TX);

}

} catch (hibernateException ex) {

Throw EX;

}

}

Public static void committransaction () throws hibernateException {

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 Of 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 he) {

HE.PrintStackTrace ();

}

}

Public ComponentDemo () throws hibernateException {

Session sess = hibernateutil.currents;

Person P = New Person ();

P.Setaddress (New Address ("China", "Shanghai", "Putuo", "200055");

P.SetuserName ("javamxj");

sess.save (p);

P = new person ();

P.Setaddress (New Address ("China", "Beijing", "Haidian", "100086"));

P.Setusername ("Zhang San");

sess.save (p);

List animals = sess.find ("from" person.class.getname ());

ITERATOR IT = Animals.Item (); it.hasnext ();) {

Person Person = (Person) IT.Next ();

System.out.println (Person.getuserName () ":" person.getaddress ());

}

Hibernateutil.closesis ();

}

}

· Run this class, the console output is as follows:

· At the same time, the following data is generated in the data sheet:

· The final project structure is as follows:

转载请注明原文地址:https://www.9cbs.com/read-36215.html

New Post(0)