Official Getting Started tutorial hibernate

2010-08-21  来源:本站原创  分类:Java  人气:310 

hibernate tutorial first part of the official entry - the first Hibernate program

First we will create a simple console (console-based) Hibernate program. We use the built-in database (in-memory database) (HSQL DB), so we do not install any database server.

Let us assume that we want to have a small program can save our hope that the attention the event (Event), and these events. (Translator's Note: Later in this tutorial, we will directly use the Event rather than its Chinese translation of the "incident" to avoid confusion.)

The first thing we do is to build our development directory, and all need to use the Java library bag. From the Hibernate website download page to download Hibernate distribution. Extract the package and the / lib all of the following library files into our new development directory below / lib directory. Looks like this:

.
+ Lib
antlr.jar
cglib-full.jar
asm.jar
asm-attrs.jars
commons-collections.jar
commons-logging.jar
ehcache.jar
hibernate3.jar
jta.jar
dom4j.jar
log4j.jar

This is the minimum set of required libraries (note that we also copied hibernate3.jar, the main archive) for Hibernate. See the README.txt file in the lib / directory of the Hibernate distribution for more information about required and optional third-party libraries. (Actually, Log4j is not required but preferred by many developers.) This is the minimum needed to run Hibernate library collection (note that we have copies of the Hibernate3.jar, this is the most important of library). Hibernate can be distributed version of lib / directory, see README.txt, to get more information on required and optional third-party library file information (in fact, Log4j is not required library files, but many developers prefer to use it ).

Next we create a class, used to represent those we wish to store in the database inside the event.
2.2.1. The first class

Our first persistent class is a simple JavaBean class, with a few simple property (property). Let us look at the code:

import java.util.Date;

public class Event (
private Long id;

private String title;
private Date date;

Event () ()

public Long getId () (
return id;
)

private void setId (Long id) (
this.id = id;
)

public Date getDate () (
return date;
)

public void setDate (Date date) (
this.date = date;
)

public String getTitle () (
return title;
)

public void setTitle (String title) (
this.title = title;
)
)

You can see the class of the property (property) access methods (getter and setter method) using the standard JavaBean naming conventions, while the internal field (field) hidden (private visibility). This is a recommended design by the way, but is not required to do so. Hibernate can also directly access these fields (field), using access methods (accessor method) is to provide the benefits of the program when the reconstruction of the robustness (robustness).

id attribute (property) to provide identification for an Event instance attributes (identifier property) value - if we want to use all the features of Hibernate, then all our persistent entity classes (persistent entity class) (This also includes some minor dependent classes ) needs a logo attribute (identifier property). In fact, most applications (particularly web applications) need to identify a specific object, so you should consider using the identifier property rather than taking it as a limit. However, we usually do not directly manipulate an object identifier (identifier), so the identifier of the setter method should be declared as private (private). So that when an object is saved when only the Hibernate distribution identifier for it. You will find direct access to Hibernate can be declared as public, private and protected access to various levels of control methods (accessor method) and field (field). So choose which way to access the property is entirely up to you, you can make your choices and your program design consistent.

All persistent classes (persistent classes) are required with or without participation in the constructor (no-argument constructor); because Hibernate must use Java reflection (Reflection) to an instance of an object. Constructor (constructor) of the access control can be private (private), but when generating run-time agent (runtime proxy) when the package will require the use of at least the level of access control, so that there is no byte-code compiled (bytecode instrumentation ) cases, from the persistent classes in a number of more efficient access to data.

We put the Java source code files into our development directory below the directory called src. This directory should now look like this:

.
+ Lib
<Hibernate And third-party libraries>
+ Src
Event.java

In the next step, we will this persistent class (persisten class) of information to inform Hibernate
2.2.2. Map file

Hibernate needs to know how to load (load) and storage (store) our persistent class object. Here is the Hibernate mapping file (mapping file) into play. Hibernate mapping file to tell it which should access the database tables inside (table) and what should be used inside the table field (column).

The basic structure of a mapping file looks like this:

<? Xml version = "1.0"?>
<! DOCTYPE hibernate-mapping PUBLIC
"- / / Hibernate / Hibernate Mapping DTD 3.0 / / EN"
"Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
[...]
</ Hibernate-mapping>

Note that Hibernate's DTD is very complex. You can in your editor or IDE which uses it to automatically prompt and complete (auto-completion) that is used to map the XML element (element) and attributes (attribute). You can also use your text editor opens DTD-This is the easiest way to browse all the elements and Shen Shu, view them in the default values, and they are the Zhushi to get a total of almost Guan. At the same time we should pay attention not Hibernate DTD files from the web to obtain the above, although the XML inside the URL might suggest it to do so, but Hibernate will first see your program's classpath. DTD file is included in the hibernate3.jar, while also Hibernate distribution of src / path.

In the next example which we will omit the DTD declaration to shorten the code length. But obviously, in the actual program, DTD declaration is necessary.

In the two hibernate-mapping tag (tag) the middle, we include a class element (element). All persistent entity classes (persistent entity classes) (Again, here too, including those dependent on class, are those secondary entities) need such a mapping, to map to our SQL database.

<hibernate-mapping>

<class name="Event" table="EVENTS">

</ Class>

</ Hibernate-mapping>

We are doing everything so far is how to tell Hibernate from the database table (table) EVENTS Event in persistence and loading the object class, each instance of the database which corresponds to a row. Now we will continue to discuss the unique identifier property (unique identifier property) mapping. In addition, we do not want to consider how to produce the identity property, we will configure the Hibernate identifier generation strategy (identifier generation strategy) to generate alternative primary key.

<hibernate-mapping>

<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator/>
</ Id>
</ Class>

</ Hibernate-mapping>

id element is the identity attribute (identifer property) of the statement, name = "id" declares the Java property (property) name - Hibernate will use the getId () and setId () to access it. Field parameters (column attribute) tells Hibernate which we use the EVENTS table as the primary key field. Nested generator element specifies the identifier generation strategy - where we use the increment, this is very simple in memory directly generate numbers, mostly for testing (or tutorial) in the. Hibernate also supports the use of the database generated (database generated), globally unique (globally unique) and the application specified (application assigned) (or your own written policy for the expansion of any existing) way to generate these identifiers.

Finally, we must also mapping file which include the need for persistent attribute of the statement. Default case, the class attribute which are considered non-persistent:

<hibernate-mapping>

<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator/>
</ Id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
</ Class>

</ Hibernate-mapping>

And id elements similar to, property element of the name parameter tells Hibernate which getter and setter methods to use.

Why date property mapping include the column parameters, but the title does not? When there is no set time column parameters, Hibernate by default uses the property name as a field (column) name. For the title, this work well. However, date in most of the database is a reserved keyword, so we had better maps it into another name.

Next interesting thing is the lack of a title attribute type parameter. We declare and use in the mapping file inside the type, not as we imagined it, is the Java data type, while not a SQL database type. These types are called Hibernate mapping types, which convert the data type from Java to SQL data types. If the map parameter is not set, then, Hibernate will try to determine the correct type of conversion and mapping of its type. In some cases this automatic detection (in the Java class using reflection) does not produce what you expect or need the default values. Here is an example of this is on the date attribute. Hibernate can not know this property should be mapped into the following which of these types: SQL date, timestamp, time. We timestamp to property mapping by a statement that we want to save all the information on the date and time.

The mapping file (mapping file) should be saved as Event.hbm.xml, and our EventJava source files in the same directory. Mapping file name can be arbitrary, but hbm.xml Hibernate developer community has become customary conventions. Directory should now look like this:

.
+ Lib
<Hibernate And third-party libraries>
+ Src
Event.java
Event.hbm.xml

We continue to Hibernate's main configuration.
2.2.3. Hibernate configuration

We now have a persistent class and its mapping file, it is time the Hibernate configuration. Before we do this, we need a database. HSQL DB, a java-based embedded SQL database (in-memory SQL Database), available from the HSQL DB's website. In fact, you only need to download / lib / directory hsqldb.jar. Development of this file folders on the lib / directory inside.

In the development of the following to create a directory called data in the directory - this is the HSQL DB data files stored in its place.

Hibernate is a program where you connect to the database of the application layer, so it needs to connect with information. Connection (connection) also by us through a JDBC connection pool configuration (connection pool). Hibernate's distribution which includes a number of open source's connection pool, but we have decided to use this tutorial embedded connection pool. If you want to use a product-level third-party connection pool software, you must copy the required library files to your classpath and use different connection pooling settings.

To configure Hibernate, we can use a simple hibernate.properties file, or a slightly more complex hibernate.cfg.xml, even fully use the program to configure Hibernate. Most users prefer to use XML configuration files:

<? Xml version = '1 .0 'encoding =' utf-8 '?>
<! DOCTYPE hibernate-configuration PUBLIC
"- / / Hibernate / Hibernate Configuration DTD 3.0 / / EN"
"Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<! - Database connection settings ->
<property name="connection.driver_class"> org.hsqldb.jdbcDriver </ property>
<property name="connection.url"> jdbc: hsqldb: data / tutorial </ property>
<property name="connection.username"> sa </ property>
<property name="connection.password"> </ property>

<! - JDBC connection pool (use the built-in) ->
<property name="connection.pool_size"> 1 </ property>

<! - SQL dialect ->
<property name="dialect"> org.hibernate.dialect.HSQLDialect </ property>

<! - Echo all executed SQL to stdout ->
<property name="show_sql"> true </ property>

<! - Drop and re-create the database schema on startup ->
<property name="hbm2ddl.auto"> create </ property>

<mapping resource="Event.hbm.xml"/>

</ Session-factory>

</ Hibernate-configuration>

Note that this XML configuration uses a different DTD. We configure Hibernate's SessionFactory-1 associated with a particular database of overall plant (factory). If you want to use multiple databases, should normally be used in multiple configuration files to configure multiple <session-factory> (in the earlier steps to start).

The beginning of the four property elements contain the necessary JDBC connection information. dialectproperty that Hibernate should generate database-specific syntax of SQL statements. hbm2ddl.auto option will automatically generate the database table definition (schema) - directly into the database. Of course, this option can be turned off (by removing the option) or by SchemaExport Ant task to define the database table into a file optimized. Finally, persistent classes to join mapping file.

Copy this file to the source code directory below, so that it is located in the root classpath path. Hibernate will automatically start when it began to look for the root of the configuration file named hibernate.cfg.xml.
2.2.4. Compile with Ant

In this tutorial, we will use Ant to compile the program. You must first install the Ant-can download it from the Ant download page. How to install Ant is not the content of this tutorial, please refer to Ant manual. When you install the finished Ant, we can begin to create a compiled script, it's file name is build.xml, put it directly on the development directory.
Improve the Ant

Note that Ant's distribution function is usually incomplete (as Ant FAQ which put it), so you always have to require yourself to improve Ant. For example: If you wish to use inside your build file JUnit function. In order to JUnit task is activated (this tutorial we do not need this task), you must copy junit.jar to ANT_HOME / lib directory or delete ANT_HOME / lib / ant-junit.jar the plugin.

A basic build file looks like this

<project name="hibernate-tutorial" default="compile">

<property name="sourcedir" value="${basedir}/src"/>
<property name="targetdir" value="${basedir}/bin"/>
<property name="librarydir" value="${basedir}/lib"/>

<path>
<fileset dir="${librarydir}">
<include name="*.jar"/>
</ Fileset>
</ Path>

<target name="clean">
<delete dir="${targetdir}"/>
<mkdir dir="${targetdir}"/>
</ Target>

<target name="compile" depends="clean, copy-resources">
<Javac srcdir = "$ (sourcedir)"
destdir = "$ (targetdir)"
classpathref = "libraries" />
</ Target>

<target name="copy-resources">
<copy todir="${targetdir}">
<fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</ Fileset>
</ Copy>
</ Target>

</ Project>

This will tell Ant to all in the lib directory to. Jar files by adding at the end of the classpath used to compile. It also will put all the non-Java source code files, such as configuration and Hibernate mapping files, copy to the target directory. If you now run Ant, you will get the following output:

C: \ hibernateTutorial \> ant
Buildfile: build.xml

copy-resources:
[Copy] Copying 2 files to C: \ hibernateTutorial \ bin

compile:
[Javac] Compiling 1 source file to C: \ hibernateTutorial \ bin

BUILD SUCCESSFUL
Total time: 1 second

2.2.5. Installation and Help

Is the time to load and store some Event objects, but first we have to do some basic code. We must start the Hibernate. This starts the process includes the creation of a global nature SessoinFactory and store it in an application where easy access. SessionFactory can create and open a new Session. A Session represents a single-threaded unit operations, SessionFactory is a thread-safe global object, only need to create one.

We will help create a HibernateUtil class (helper class) to be responsible and to start the Hibernate Session easy operation. This helper class will use the model known as ThreadLocal Session to ensure that the current unit operation and the current thread is associated. Let's look at one of its implementation:

import org.hibernate .*;
import org.hibernate.cfg .*;

public class HibernateUtil (

public static final SessionFactory sessionFactory;

static (
try (
/ / Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration (). configure (). buildSessionFactory ();
) Catch (Throwable ex) (
/ / Make sure you log the exception, as it might be swallowed
System.err.println ("Initial SessionFactory creation failed." + Ex);
throw new ExceptionInInitializerError (ex);
)
)

public static final ThreadLocal session = new ThreadLocal ();

public static Session currentSession () throws HibernateException (
Session s = (Session) session.get ();
/ / Open a new Session, if this thread has none yet
if (s == null) (
s = sessionFactory.openSession ();
/ / Store it in the ThreadLocal variable
session.set (s);
)
return s;
)

public static void closeSession () throws HibernateException (
Session s = (Session) session.get ();
if (s! = null)
s.close ();
session.set (null);
)
)

This class not only in its static initialization (only when the load when the class is the implementation of a JVM) produced in the global SessionFactory, but also a ThreadLocal variable to the current thread is saved Session. Whenever you call HibernateUtil.currentSession (), it always returns the same thread in the same Hibernate unit operation. And a HibernateUtil.closeSession () call will terminate the current thread linked to the unit operation.

In the class before you use this to help make sure you understand the Java on the local thread variable (thread-local variable) concept. A more powerful HibernateUtil helper class can CaveatEmptorhttp: / / caveatemptor.hibernate.org / find - it also appears in the book: "Hibernate in Action" in. Note that when you deploy Hibernate in a J2EE application server, when the class is not necessary: a Session will be automatically bound to the current JTA things, you can JNDI to find the SessionFactory. If you are using JBoss AS, Hibernate can be deployed as a managed system services (system service) and automatically bind the SessionFactory to JNDI.

HibernateUtil.java on the development of the directory path to the source code below, together with Event.java:

.
+ Lib
<Hibernate And third-party libraries>
+ Src
Event.java
Event.hbm.xml
HibernateUtil.java
hibernate.cfg.xml
+ Data
build.xml

Re-compile this program should not be a problem. Finally, we need to configure a logging system - Hibernate uses common logging interface, which allows you to Log4j and JDK 1.4 logging to choose between. Most developers prefer Log4j: Hibernate distribution from the version (it etc / directory) copy log4j.properties to your src directory, and hibernate.cfg.xml. Together. Look at the configuration example, you can modify the configuration if you want to see more of the output. By default, only Hibernate startup message will be displayed in the standard output.

Tutorial of the basic framework done - now we can use Hibernate to do the real work.
2.2.6. Load and store objects

Finally, we can use Hibernate to load and store object. We write with a main () method of the EventManager class:

import org.hibernate.Transaction;
import org.hibernate.Session;

import java.util.Date;

public class EventManager (

public static void main (String [] args) (
EventManager mgr = new EventManager ();

if (args [0]. equals ("store")) (
mgr.createAndStoreEvent ("My Event", new Date ());
)

HibernateUtil.sessionFactory.close ();
)

)

We read some of the parameters from the command line, if the first parameter is the "store", we create and store a new Event:

private void createAndStoreEvent (String title, Date theDate) (
Session session = HibernateUtil.currentSession ();
Transaction tx = session.beginTransaction ();

Event theEvent = new Event ();
theEvent.setTitle (title);
theEvent.setDate (theDate);

session.save (theEvent);

tx.commit ();
HibernateUtil.closeSession ();
)

We create a new Event object and pass it to Hibernate. Hibernate is now responsible for creating SQL INSERT command and to pass on the database. Before running it, let's spend some time in the Session and Transaction handling code.

Each Session is an independent unit operations. You will we have another API: Transaction and surprised. This implies that a unit operation can have a single database transaction than a longer life cycle - imagine the web application, a unit operation across multiple Http request / response cycle (such as a create dialog). According to "application user in the eyes of the unit operations" to cut services is one of Hibernate's basic design. We call a long life of the unit operations Application Transaction, it is usually packed on a few more short life database transactions. To simplify the problem, in this tutorial we use Session and Transaction is 1 to 1 relationship between the size (one-to-one granularity).

Transaction.begin () and commit () all do? rollback () the circumstances under which generates an error? Hibernate Transaction API is actually optional, but we often convenience and portability to use it. If you prefer to handle database transaction (for example, call session.connection.commit ()), through direct and non-management, JDBC, this code will bind to a specific deployment environments. Hibernate configuration by setting Transaction factory, you can deploy your persistence layer in any place. See Chapter 12 Services and complicated to learn more about transaction processing and classification of information. In this example, we ignore any exception handling and transaction rollback.

In order to run our first application, we must add a target that can be called to Ant's build file.

<target name="run" depends="compile">
<java fork="true" classname="EventManager" classpathref="libraries">
<classpath path="${targetdir}"/>
<arg value="${action}"/>
</ Java>
</ Target>

action parameter in the command line when calling the target set:

C: \ hibernateTutorial \> ant run-Daction = store

You should see, after the end of compilation, Hibernate configuration according to your boot, and generate a lot of the output log. Finally you will see in the log the following line:

[Java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?,?,?)

This is the Hibernate implementation of the INSERT command, the pending question mark on behalf of JDBC bind parameters. If you want to see the bound value of the parameter or reduce the length of the log, check your settings in the log4j.properties file.

Now we want to list all have been stored in the event, so we add a conditional branch to the main method to options.

if (args [0]. equals ("store")) (
mgr.createAndStoreEvent ("My Event", new Date ());
)
else if (args [0]. equals ("list")) (
List events = mgr.listEvents ();
for (int i = 0; i <events.size (); i + +) (
Event theEvent = (Event) events.get (i);
System.out.println ("Event:" + theEvent.getTitle () +
"Time:" + theEvent.getDate ());
)
)

We also add a new listEvents () method:

private List listEvents () (
Session session = HibernateUtil.currentSession ();
Transaction tx = session.beginTransaction ();

List result = session.createQuery ("from Event"). List ();

tx.commit ();
session.close ();

return result;
)

We are here with a HQL (Hibernate Query Language-Hibernate Query Language) query to load from the database of all existing Event. Hibernate will generate the correct SQL, send a query to the database and use the data to generate the Event object. Of course, you can also use the HQL to create more complex queries.

If you use the command line parameter-Daction = list to run Ant, you will see that so far we have saved the Event. If you follow along step by step for this tutorial, you may be surprised this does not work - the result is always empty. The reason is hbm2ddl.auto open a Hibernate configuration option: This allows Hibernate to run at each time to re-create the database. Delete this from the inside through the configuration option to disable it. After running the store several times, then run the list, you will see the results appear in the list. In addition, the automatic generation of database tables and export in unit testing is very useful.
2.3. Part II - Correlation Map

We have mapped a persistent entity class to a table. On this basis, we increase the correlation between the number of classes. First we go to our procedures which increase a person (people) of the concept, and store their participation in an Event list. (Translator's Note: As with the Event, we will be directly behind the tutorial person to represent "people" rather than its Chinese translation)
2.3.1. Mappings Person class

The original Person class is simple:

public class Person (

private Long id;
private int age;
private String firstname;
private String lastname;

Person () ()

/ / Accessor methods for all properties, private setter for 'id'

)

Create a new mapping file called Person.hbm.xml:

<hibernate-mapping>

<class name="Person" table="PERSON">
<id name="id" column="PERSON_ID">
<generator/>
</ Id>
<property name="age"/>
<property name="firstname"/>
<property name="lastname"/>
</ Class>

</ Hibernate-mapping>

Finally, add the new mapping to Hibernate's configuration:

<mapping resource="Event.hbm.xml"/>
<mapping resource="Person.hbm.xml"/>

We are now the two entities will create an association between classes. Obviously, person can participate in a series of Event, and Event participants have different (person). Design we need to consider the question above is associated with the direction (directionality), the order (multiplicity) and the set (collection) of the act.
2.3.2. A one-way Set-based association

Person class we will be adding a group of Event. So that we can easily by calling aPerson.getEvents () to get a Person participates in the Event list, without having to perform an explicit query. We use a set of Java classes: a Set, because Set does not allow duplicate elements, including sorting and has nothing to do with us.

So far we have designed a one-way, there are many values at one end of the corresponding correlation, achieved through the Set. Let us for this in the Java class in coding and mapping of this association:

public class Person (

private Set events = new HashSet ();

public Set getEvents () (
return events;
)

public void setEvents (Set events) (
this.events = events;
)
)

In our mapping of this association before the association to consider the other end. Clearly, we can keep this association is a one-way. If we hope that this association is bidirectional, we can create another Event in a collection, such as: anEvent.getParticipants (). This is a design option left to you, but from this discussion, we can clearly understand what is the order of association (multiplicity): both ends of this association is "more." We call this as: many to many (many-to-many) association. Therefore, we use Hibernate's many-to-many mapping:

<class name="Person" table="PERSON">
<id name="id" column="PERSON_ID">
<generator/>
</ Id>
<property name="age"/>
<property name="firstname"/>
<property name="lastname"/>

<set name="events" table="PERSON_EVENT">
<key column="PERSON_ID"/>
<many-to-many column="EVENT_ID"/>
</ Set>

</ Class>

Hibernate supports all kinds of collection mappings, <set> is the most commonly used. For many to many (many-to-many) association (or called n: m entity relationship), need a table to store the associated (association table). Each row represents a table inside a person to an event from an association. Table name is set the table element attribute value configured. Inside the field names associated with identity, person at one end, is defined by the <key> element, event end of the field name column by <many-to-many> element attribute definitions. You also have to tell Hibernate the class of objects in the collection (that is, represented in this collection associated with the other end of the class).

The mapping of database table defined as follows:

_____________ __________________
| | | | _____________
| EVENTS | | PERSON_EVENT | | |
|_____________| |__________________| | PERSON |
| | | | |_____________|
| * EVENT_ID | <-> | * EVENT_ID | | |
| EVENT_DATE | | * PERSON_ID | <-> | * PERSON_ID |
| TITLE | |__________________| | AGE |
|_____________| | FIRSTNAME |
| LASTNAME |
|_____________|

2.3.3. So that the work associated

Let us put some people and the event EventManager a new method:

private void addPersonToEvent (Long personId, Long eventId) (
Session session = HibernateUtil.currentSession ();
Transaction tx = session.beginTransaction ();

Person aPerson = (Person) session.load (Person.class, personId);
Event anEvent = (Event) session.load (Event.class, eventId);

aPerson.getEvents (). add (anEvent);

tx.commit ();
HibernateUtil.closeSession ();
)

In Person and an Event load after a simple modification using the ordinary method of collection. As you can see, there is no explicit update () or save (), Hibernate automatically detects that the collection has been modified and needs to be saved. This is called automatic dirty checking, you can try to modify any object's name or date parameters. As long as they are in persistent state, that is, bound in a Hibernate Session (for example: they had just been loaded from a unit operation or save), Hibernate monitors any changes and implicitly in the background, the implementation of SQL. Memory state and the database synchronization process, usually in a unit operation occurs at the end of this process is called flushing.

Of course you can also load a different person inside the unit operations and event. Or other changes in a Session is not in a persistent (persistent) state of the object (if the object previously had been persistent, we call this state detached (detached)). In a program looks like this:

private void addPersonToEvent (Long personId, Long eventId) (

Session session = HibernateUtil.currentSession ();
Transaction tx = session.beginTransaction ();

Person aPerson = (Person) session.load (Person.class, personId);
Event anEvent = (Event) session.load (Event.class, eventId);

tx.commit ();
HibernateUtil.closeSession ();

aPerson.getEvents (). add (anEvent); / / aPerson is detached

Session session2 = HibernateUtil.currentSession ();
Transaction tx2 = session.beginTransaction ();

session2.update (aPerson); / / Reattachment of aPerson

tx2.commit ();
HibernateUtil.closeSession ();
)

Call on the update to a detached object (detached object) re persistent, you can say it was bound to a new unit operation, so any of you off it in the tube (detached) state changes are made be saved to the database.

The current situation of our not very useful, but it is a very important concept, you can design it into your own program. Now, add a new option to the EventManager's main method and run it from the command line to complete this exercise. If you need a person and an event identifier - save () to return it. ******* Do not understand this last sentence to see

The above is a kind of equal status on the two examples of correlation, which is in between the two entities. As previously mentioned, there are other special classes and types, these classes and types are usually "secondary." Some of you have seen, like int or String. We call these classes as value types (value type), their examples rely (depend) on a specific entity. These types of examples do not identify themselves (identity), can not be shared between the entities (such as two person can not reference the same firstname object, even if they have the same name). Of course, value types do not just exist in the JDK (in fact, in a Hibernate program, all the JDK classes are considered value types), you can write your own dependency classes, such as Address, MonetaryAmount.

You can also design a collection of value type (collection of value types), this concept with the entities in the collection are very different, but in Java which looks almost the same.
2.3.4. A collection of value types

We set a value type object accession Person. We want to save email addresses, so we use String, but this type of collection is Set:

private Set emailAddresses = new HashSet ();

public Set getEmailAddresses () (
return emailAddresses;
)

public void setEmailAddresses (Set emailAddresses) (
this.emailAddresses = emailAddresses;
)

Set the map

<set name="emailAddresses" table="PERSON_EMAIL_ADDR">
<key column="PERSON_ID"/>
<element type="string" column="EMAIL_ADDR"/>
</ Set>

Comparing this and the earlier start of the mapping, the difference mainly in the part of the element does not include references to other entity types, but use a collection element type is String (the lowercase name used here is to show you that it is a Hibernate map type or the type converter). As before, set the parameters of the decision table database table name for the collections. key elements of the definition used in the tables in the collection of foreign keys. element element of the column parameters of the definition of the actual stored value of the field name String.

Look at the modified database table definition.

_____________ __________________
| | | | _____________
| EVENTS | | PERSON_EVENT | | | ___________________
|_____________| |__________________| | PERSON | | |
| | | | |_____________| | PERSON_EMAIL_ADDR |
| * EVENT_ID | <-> | * EVENT_ID | | | |___________________|
| EVENT_DATE | | * PERSON_ID | <-> | * PERSON_ID | <-> | * PERSON_ID |
| TITLE | |__________________| | AGE | | * EMAIL_ADDR |
|_____________| | FIRSTNAME | |___________________|
| LASTNAME |
|_____________|

You can see the collection table (collection table) in fact the primary key is a compound primary key, using the two fields. This also implies that the same person can not have duplicate email addresses, this is to use Java inside when needed semantic Set (Set in element can not be repeated).

You can now try to include the element of this collection, as we have before the person and event as related. Java code is the same inside.
2.3.5. Bidirectional association

Now we will map a bidirectional association (bi-directional association) - in Java so that person and the event which can be associated with any side to visit the other side. Of course, the database table definition has not changed, we still need many to many (many-to-many) of the order (multiplicity). A relational database programming language is more flexible than the network, so it does not need any direction, like navigation (navigation direction) of things - data can be used in any way possible to view and access.

First of all, a participant (person) Event set to join the class:

private Set participants = new HashSet ();

public Set getParticipants () (
return participants;
)

public void setParticipants (Set participants) (
this.participants = participants;
)

In Event.hbm.xml which also mapped the association.

<set name="participants" table="PERSON_EVENT" inverse="true">
<key column="EVENT_ID"/>
<many-to-many column="PERSON_ID"/>
</ Set>

As you can see, the two mapping file has the usual set mapping. Note key and many-to-many field names inside the files in the two maps is commutative. The important difference here is the Event mapping file set element inverse = "true" parameter.

This indicated that Hibernate needs to find the correlation between the two entities of information, it should use the other end of the association - Person class. This will greatly help you understand how the bidirectional association between the two entities in our created.
2.3.6. To work a two-way association

First of all, keep in mind that in mind, Hibernate does not affect normal Java semantics. In the one-way association, how we in a Person and an Event create a link between? We have an instance of an Event Add a Person class in the Event collection. So, obviously, we want this association in both directions, we need to do the same thing the other end - to add an Event class Person Person within the collection. This "set both ends of the associated connection" is absolutely necessary and you should never forget to do it.

Many developers through the creation of management-related approaches to ensure the correct set both ends of the association, such as Person in:

protected Set getEvents () (
return events;
)

protected void setEvents (Set events) (
this.events = events;
)

public void addToEvent (Event event) (
this.getEvents (). add (event);
event.getParticipants (). add (this);
)

public void removeFromEvent (Event event) (
this.getEvents (). remove (event);
event.getParticipants (). remove (this);
)

Note now get and set for the collection methods of access control level is protected - this allows in the same package (package) in the class and inherit from a subclass of this class can access these methods, but against other direct external access, avoid the collection of the contents of the confusion. You should as much as possible in the collection corresponding to the other side do the same.

inverse mapping parameters really mean it? For you and for Java is a bidirectional association is just a simple setting in both ends of the reference. However, only that Hibernate does not have enough information to generate the correct INSERT and UPDATE statements (to avoid constraint violation of the database), so Hibernate need some help to correctly handle bidirectional associations. The inverse association end of the set to tell Hibernate to ignore the relevance of this side, this side is the other end as a mirror (mirror). This is the information needed to Hibernate, Hibernate how to use it to process the data into a navigation model is mapped to a relational database table definition. You just need to remember the following rules of this intuitive: the need for all two-way association end is set to inverse. In a one to many (one-to-many) association it must be representative of many (many) of the end of the line. In many to many (many-to-many) association, you can choose any side, there is no difference between the two ends.
2.4. Summary

This tutorial covers a simple Hibernate on the development of some fundamental aspects of the application.

相关文章
  • Official Getting Started tutorial hibernate 2010-08-21

    hibernate tutorial first part of the official entry - the first Hibernate program First we will create a simple console (console-based) Hibernate program. We use the built-in database (in-memory database) (HSQL DB), so we do not install any database

  • mysql5.1 official Chinese language tutorial 2010-06-13

    Tutorial Address http://dev.mysql.com/doc/refman/5.1/zh/

  • The first tutorial, Hibernate 2010-08-24

    "> First Hibernate project 1. Start MySQL Service D: \ DataBase \ mysql-program \ bin \ mysqld-nt.exe 2. New Java Project 3. Guided package Hibernate and MySQL Bulid Path-> Add Library-> User Library-> ... 4. New hibernate.cfg.xml <? X

  • Complete Hibernate 3.0 Tutorial 2009-09-05

    This tutorial provide step by step instructions on using Hibernate 3.0. Hibernate is popular open source object relational mapping tool for Java platform. It provides powerful, ultra-high performance object / relational persistence and query service

  • Official Google chrome plug Tutorial 2010-04-20

    JE has a way to see the article on: http://www.javaeye.com/topic/646674 content is to do two chrome plug-in, saw a lot of people are interested in this, little brother to go online read over the pages of the special , finally found the official chrom

  • Hibernate mapping file configuration 2009-09-04

    Object-relational mapping is an XML document to illustrate the. Document mapping tools can be used to generate, such as XDoclet, Middlegen and so on AndroMDA. The following example from the beginning of a map on the mapping element of the code mappin

  • Hibernate Avg () 2009-09-05

    package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateHQLAv

  • Hibernate Projection Example (Sum) 2009-09-05

    package roseindia.tutorial.hibernate; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.ProjectionList; impo

  • Git Chinese Tutorial 2010-04-13

    Thank http://www.bitsun.com/documents/gittutorcn.htm Share Introduction Git --- The stupid content tracker, stupid content tracker. Linus is so Git give us the. Git is the version for Linux kernel development control tool. With the commonly used vers

  • basic configuration hibernate 2010-10-24

    1. Development Environment Window 2. Development Tools MyEclispe5.x 3.JDK1.5 4. Must be using the hibernate package can be used MyEclipse own (mine is), or the official website http://www.hibernate.org/ package containing the corresponding 5. Using j

  • Rails3 one tutorial series: Rails3 Getting Started 2010-11-22

    Article Source: http://edgeguides.rubyonrails.org/getting_started.html Then pick up the time that has come to Rails 3.0.3, the huge change that can not find tutorial to find articles in Chinese, has decided to side according to the official translati

  • The Collection type hibernate 2011-01-09

    Collection type: In Hibenrate the many, many to many relationship, Collection of the more important position occupied; in Hibernate to support several types of Collection? What is the difference between them? Collection involved in the Hibernate type

  • SQL optimistic locking and pessimistic locking 2010-03-20

    Lock (locking) The implementation of business logic, the need to ensure that data access is often exclusive. Such as the end of the day in the financial settlement processing system, we hope for a cut-off time data processing, would not want to carry

  • SQL Procedural Language Summary 2010-05-27

    Wuxi starting from last Sunday to learn DB2 application development has been, is finally finished study. Because knowledge work is usually used, although the work part of the process has accumulated, but are more complex, so the official website IBM

  • day2 learning orientation + Maps API 2010-07-01

    Task is to make a cell phone camera + positioning + map application of common Today, the official made a tutorial example of positioning + map to find out API. Examples of official photographs could not find examples of blind search of the examples d

  • perl Learning Resources 2010-09-26

    One, Perl Introduction Perl is an advanced, universal, literal translation, dynamic programming language. Its features are: flexibility of a large, redundant are also great, easy to read. Perl5 has been issued, Perl being developed. Perl Wikipedia Se

  • A website providing free space jsp (rpm) 2010-11-08

    Articles Category: Java Programming Keywords: A website providing free space jsp EATJ the United States to provide free JSP hosting jsp space applications, 50M space, monthly traffic limits 3G support Java5.0/6.0, PHP, CGI, Perl, SSI, etc., to provid

  • Configuring single sign-on for the sakai 2010-11-22

    sakai: 2.7.1 cas-server: 3.4.3.1 cas-client: 3.1.12 On how to configure single sign-sakai official has a tutorial, http://confluence.sakaiproject.org/display/ ~ steve.swinsburg / CASifying + Sakai. But inside the cas-client version to use lower cas p

  • Introduction rails (1) build environment 2011-04-26

    Article Source: http://edgeguides.rubyonrails.org/getting_started.html Transfer from: http://onia.iteye.com/blog/819762 Then pick up the time that has come to Rails 3.0.3, the huge change that can not find tutorial to find articles in Chinese, has de

  • How to solve the MySQL master-slave mode, the use of ReplicationDriver 2011-01-11

    Introduction: Before the downpour with a paste (http://www.iteye.com/topic/143714) discusses how to use mysql in java the master-slave mode (master-slave mode description, see Qieqie this paste: http:// www.iteye.com/topic/162717), which greatly that