Hibernate Quick Start

Hibernate Framework
Hibernate Framework
Hibernate Quick Start
Hibernate based on semantic
Hibernate configuration basis
Hibernate O / R Mapping
Hibernate Data Association
Hibernate data retrieval
HQL practical technology
Hibernate advanced features
Hibernate Quick Start
OR mapping is a development issue has been the most complex issues, has not been a very good solution to the current OR known solutions are:
1, entity EJB, mainly refers to the way CMP entity EJB
2, JDO, Java Data Object to try to resolve the problems EJB
3, TopLink, WebGain company's products, Oracle is now the acquisition of
4, Hibernate
Hibernate Quick Start
Hibernate and Struts, the open source project is to provide a framework for the realization of OR mapping, management of the project organization is JBoss
Hiberate was born in November 2001, Gavin King is the personal works in his spare time, JBoss was adopted, as its main force to promote their products
Gavin King has become a member EJB3.0 experts, JBoss
Core members, was born in 74 years,
People in Melbourne, Australia.
Hibernate Quick Start
Gavin King first worked for an IT company in Sydney, Australia, Cirrus Technologies, in determining the development of Hibernate when, Gavin King knew nothing of SQL.
September 2003, Gavin King, and some hibernate developers joined JBoss, specializing in the development of Hibernate in the Sun to develop EJB3.0 company, he became the de facto leader
Gavin King has a statement on the site if someone can use to write Java code efficient than Hibernate fragment, he is willing to pay for each code section of 100 U.S. dollars
Hibernate Quick Start
Hibernate is the core idea of the data in the database will be mapped to the JavaBean object, and object properties directly to the data, wrote the corresponding fields on the database.
Hibernate said JavaBean used to store data for POJOs (Plain Old Java Objects, also called Plain Ordinary Java Objects)
Important issues to be addressed is the JavaBean properties of each object with which a table which corresponds to a field
Hibernate Quick Start, such as objects are defined as follows:
public class User (
private String id;
private String userId;
private String password;
public String getId () (
return id;
)
public void setId (String id) (
this.id = id;
)
... ... ... ... ....
)
Hibernate Quick Start
Hibernate core of the interface is Session, database operations through this interface.
For example:
Configuration cfg = new Configuration ();
SessionFactory factory = cfg.configure (). BuildSessionFactory ();
Session session = factory.openSession ();
Transaction tx = session.beginTransaction ();
User user = new User ();
user.setUserId ( "teacher");
user.setPassword ( "teacher");
session.save (user);
tx.commit ();
session.close ();
Which, session is Hibernate in the Session, the same code above insert statement.
Hibernate Quick Start To achieve the above results, it is necessary to solve two problems, first, to mask the differences between different databases, and the other is to the object and the mapping table.
Hibernate configuration files through the solution to the above problem, there are two types of configuration files, a configuration information database known as the Hibernate configuration, another configuration of the object and the mapping table called Hibernate mapping of these two configurations are the form of XML documents can be configured
Hibernate Quick Start
Hibernate configuration:
<? 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>
<property name="dialect"> org.hibernate.dialect.MySQLDialect </ property>
<property name="show_sql"> true </ property>
<property name="connection.datasource"> java: comp / env / jdbc / DataSource </ property>
<mapping resource="user.xml"/>
</ session-factory>
</ hibernate-configuration>

Hibernate Quick Start
dialect: configure SQL dialects, as long as the database role is to reflect the differences between the SQL language
show_sql: run-time whether the SQL statement in the console print
connection.datasource: Hibernate to use the data source JNDI name
mapping: the configuration file specified POJO

Hibernate Quick Start
Hibernate object mapping:
<? 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>
<class name="cn.com.lhhc.hibernate.first.dao.User" table="user">
<id name="id" column="id">
<generator/>
</ id>
<property name="userId" column="userid"/>
<property name="password" column="password"/>
</ class>
</ hibernate-mapping>

Hibernate Quick Start
class designated table which corresponds with the POJO
id attributes which specify the main class key, with which the corresponding field
the definition of the type of property field attributes and relationship between

Hibernate Quick Start hibernate.cfg.xml file a SessionFactory with a corresponding, SessionFactory not lightweight, Hibernate suggested that only one application instance to create a SessionFactory
Non-thread-safe Session object, and therefore must ensure that in the development of a thread to create a session only
Therefore, one should solve two problems, first, applications throughout the SessionFactory that there is only one, the Second Session of each thread is the only one. Hibernate gives a solution of the recommendations:
Hibernate Quick Start
public class HibernateUtil (
private static final SessionFactory sessionFactory;
static (
try (
sessionFactory = new Configuration (). configure (). buildSessionFactory ();
) Catch (HibernateException ex) (
throw new RuntimeException (ex.getMessage (), ex);
)
)
public static final ThreadLocal session = new ThreadLocal ();
public static Session currentSession () throws HibernateException (
Session s = (Session) session.get ();
if (s == null) (
s = sessionFactory.openSession ();
session.set (s);
)
return s;
)
public static void closeSession () throws HibernateException (
Session s = (Session) session.get ();
session.set (null);
if (s! = null) s.close ();
)
)
Hibernate Quick Start
SessionFactory using a single-case model to ensure that there is only an example of the overall situation
Session adopted the thread local variable (ThreadLocal) approach to ensure that only one thread in the above example, there is a Session only for Hibernate2, in Hibernate3 provides a SessionFactory in getCurrentSession ways to ensure that the threads in the uniqueness of Session
Hibernate Quick Start
getCurrentSession when the first call to create a new instance, after the return has been called an example of the Session.
At the same time, Hibernate also ensure that the end of the thread, or services to submit to close Session
GetCurrentSession need to use the configuration to add
<property name="current_session_context_class">
thread
</ property>
Hibernate Quick Start code should be amended to read:
Session session = factory.getCurrentSession ();
session.beginTransaction ();
User user = new User ();
user.setUserId ( "teacher");
user.setPassword ( "teacher");
session.save (user);
session.getTransaction (). commit ();
Summary
Hibernate data objects using POJO said:
Object properties table field values and the corresponding;
A JavaBean is usually a table with the corresponding category;
JavaBean object with a line that corresponds to the table.
JavaBean and the mapping table is defined by the XML document.
Summary
Hibernate in the database operations to be completed by the Session object, Session non-thread-safe, we must ensure that a thread that there is only one Session object
Hibernate2 recommended the use of ThreadLocal object Session object to save
Hibernate3 provides getCurrentSession, but to sum up SessionFactory configured accordingly
Session object SessionFactory created by, SessionFactory from hibernate.cfg.xml file to configure a SessionFactory with a corresponding hibernate.cfg.xml, specifically the use of specified information, such as what kind of database.
Non-lightweight SessionFactory, and an application there is only one of the best SessionFactory object, the use of single-case model
Hibernate based on semantic
Configuration
SessionFactory
Session
Configuration
Configuration of the Hibernate type responsible for the management of configuration information
Hibernate runtime needs access to the bottom of the realization of some basic information, these attributes can hibernate.cfg.xml or set hibernate.properties
Configuration
When you call Configuration config = new Configuration (). Configure (); Hibernate will automatically search in the current Classpath in the hibernate.cfg.xml file and loaded into memory
Configuration
Configuration category generally involved in obtaining SessionFactory, when the creation of SessionFactory instances, because configuration information has been returned by the Hibernate's SessionFactory binding, and therefore no longer used under normal circumstances Configuration
If you do not use the default hibernate.cfg.xml, you can specify:
Configuration config = new Configuration (). Configure (new File ( "c: \ \ sample \ \ myhibernate.xml"));
SessionFactory
Session object SessionFactory been responsible.
SessionFactory
sessionFactory = config.buildSessionFactory ();

The corresponding SessionFactory save the current configuration of all the mapping database relations, but also responsible for the maintenance of the current data cache and 2 Statement Pool.
Session
Session Persistence Hibernate operation is the basis.
Session here HttpSession with the web layer does not matter, Hibernate Session with Hibernate, the equivalent of the JDBC Connection with JDBC
Insert, delete, update the corresponding session can save, delete, update methods

Session
More complex query by primary key queries can get through the session or the load
With the conditions of the inquiry, called the find, can Query, Criteria.
Session of createQuery, createCriteria methods Query, Criteria
Query and Criteria The difference is, Query-oriented HQL and Native SQL, which provides object-oriented Criteria query mode.

Hibernate configuration basis
SessionFactory Configuration Management
SessionFactory configuration database connection to configure JDBC Connection Configuration: dialect, driver_class, url, username,
password
JNDI Connection Configuration: datasource, user, pwd, dialect
Four types of database connection pool configuration connection pool: default database connection pool, C3P0, dbcp, Proxool, recommended dbcp
Configuration Management Database Connectivity JDBC Connection Configuration: dialect, driver_class, url, username, password
JNDI Connection Configuration: datasource, user, pwd, dialect
Four types of database connection pool configuration connection pool: default database connection pool, C3P0, dbcp, Proxool, recommended dbcp
Hibernate O / R Mapping
Hibernate mapping the basic data type entity Senior Mapping composite primary key entity mapping strategies
O / R mapping Introduction
Hibernate is the core idea of the database field is mapped to JavaBean properties, so clearly a JavaBean property mapping and database mapping file it is very important
Hiberante by the data, delete, change is around the start of Java objects, rather than directly in the database, so only the properties of Java objects on the statement of the will for a lasting impact on the database
O / R mapping Introduction
<? 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>
<class name="dao.User" table="user">
<id name="id" column="id">
<generator/>
</ id>
<property name="userId" column="userid"/>
<property name="password" column="password"/>
</ class>
</ hibernate-mapping>
O / R mapping Introduction
POJO type mapping table is done through the class identifier property mapping and primary key id and through the realization of composite-id, which for a joint primary key, but also need to specify the primary key attributes and the generator field mapping is done through the property element

Hibernate basic data types in Hibernate entity relationship attribute definition, the need to provide the data type attribute set through the definition of these types, Hibernate complete Java data types to the database specific data types of mapping relations.
Basic data types simple Hibernate configuration fragment attributes:
<property name="age" type="integer" column="age"/>
Integer types of properties will be mapped to the database table age field age
Hibernate provide rich data types support, including the traditional Java data types, such as String, integer, and JDBC data types, such as Clob, Blob and so on. In addition, Hibernate also provides user-defined data type support.
Hibernate basic data types
Java primitive types:
Hibernate basic data types of major data types: the database as a result of the realization of the mechanism of the difference between that for the data difficult to access general
Hibernate other types of basic data types:
Entity mapping entity class and mapping technology as a link between tables in the ORM plays a crucial role.
For Hibernate, the mapping relationship between the more reflected in the configuration file maintenance process.
Choose Hibernate mapping XML configuration files as the basis for mapping a three-part form of physical entities on the basis of high-level mapping mapping mapping entities in a three-part strategy for mapping entities on the basis of introducing Hibernate mapping entities in the category / table mapping, property / field mapping of the basic skills Advanced mapping technology to introduce the custom data types, composite primary key, a special field (Blob / Clob) technology related to mapping.
Physical mapping strategy for mapping entities around the entity size, level of design ideas to explore. Special circumstances of the logic and physical structure, performance-related entities to read and write the number of universal design strategies to introduce the basis of physical mapping of the core content of mapping entities, that is, entity classes and the mapping between database tables definition
Mapping between the type of table includes 3 parts:
Table name - class name mapping, the primary key mapping, field mapping based on entity type mapping table mapping: <class name="com.TUser" table="T_User">
Primary key mapping: <id name="id" column="id" type="java.lang.Integer"> <generator"native"> </ id>
Native means that the primary key generated by the Hibernate processing, database calls to generate their own way of the primary key attribute / fields mapping configuration: <property name="name" column="name" type="java.lang.String"/>
Advanced mapping technology
Hibernate can meet the most basic data types of application requirements.
For special circumstances, for the unity of design, we need data structures that may be repeated a number of data model, the introduction of custom data types.
Little use of advanced mapping technology
Hibernate, the composite-id node through the composite primary key defined for the composite primary key, we can see two ways to determine the primary key attributes based on the entity class based on the composite primary key Composite primary key primary key class
Hibernate in createBlob and createClob methods, the creation of Blob, Clob object. Blob object FileInputStream on which to build, Clob Construction String-based mapping strategy for Hibernate entities, the so-called fine-grained object model, is mainly designed for the target entity class breakdown, a breakdown of the main targets for two purposes:
Design-oriented sub-particle size (through the object detail and realize more clearly the logic of the system),
Performance-oriented sub-particle size (for business logic, by a reasonable fine-grained objects to improve the energy consumption ratio (performance, resource consumption))
Physical mapping strategy for the design of the size of a table can be broken down more than the corresponding entity class.
Single table for a breakdown of the object, in Hibernate can be defined with the completion of Component node.
Component with the fundamental difference between physical objects is that there is no Component logo (identity), as a logical component it is entirely subordinate to the target entity.

<class name="" table="T_USER">
<id …> </ id>
<component name="name""">
<property …/>
<property …/>
</ component>
...
</ class>
Physical mapping strategy for the performance of particle size breakdown:
For some Clob, Blob fields, the higher the cost of the database to read, I hope the real way to get called when the corresponding real data read from the database. Hibernate2 used to complete the succession. The high cost of data written on the sub-category.
Xml in the sub-category of writing:
<class name="" table="" polymorphism="explicit">
Entity-level design entity-level design: the relationship is the relationship between the succession of data and object-oriented data structure, one of the main differences between. How relational database based on the succession of relations through clear delineation of a reasonable level is Hibernate entity-level design of a key issue.
Hibernate supports three kinds of types of inheritance:
Table per concrete class (TPC)
Table with the type of one-on-one relationship between the independent
Table per subclass (TPS)
Each sub-class corresponds to a sub-table, and shared with the main categories of the main table
Table per hierarchy (TPH)
Table with the kind of one-to-many relationship between the inheritance-TPC
TPC cases, each corresponding to a specific type of form, whether it is the father of sub-class or type, as long as the abstract class rather than have a corresponding table.
Table with the main table does not exist between the corresponding foreign key relations, data redundancy
TPC, the primary key identity generator can not be used, and must ensure that sub-table of field names and the parent table field names identical to the succession-TPC
<class name="Course" abstract="true">
<id name="id" column="course_id" type="string" length="128">
<generator />
</ id>
<property name="name" column="course_name" />
<property name="period" column="total_period" />
<property name="notes" />
<union-subclass name="PractiseCourse" table="practise_course">
<property name="projectName" column="project_name" />
<property name="projectPeriod" column="project_period" />
</ union-subclass>
<union-subclass name="CertificationCourse" table="certification_course">
<property name="certificationName" column="cert_name" />
<property name="examTime" column="exam_time"/>
</ union-subclass>
</ class>
Inheritance-TPC
In operation, TPC and the other two ways the same can also be multi-modal information, multi-state insertion
List gc = session.createQuery ( "from Course"). List ();
List pc = session.createQuery ( "from PractiseCourse"). List ();
List cc = session.createQuery ( "from CertificationCourse"). List ();
Iterator it = pc.iterator ();
while (it.hasNext ()) (
Course c = (Course) it.next ();
System.out.println (c.getName ());
)
Union keywords used to load the succession-TPS
In TPH, because different sub-category contains different field values, so the inevitable time in the table of the field, a waste of storage space more serious departure from the database table design should be the field of non-common set up a separate table A total of data in another table.
This requires that each category corresponds to a single table, maintaining a sub-class table to the parent category of the foreign key table.
Inheritance-TPS
Inheritance-TPS
<class name="Course" table="course">
<id name="id" column="course_id">
<generator />
</ id>
<property name="name" column="course_name" />
... ...
<joined-subclass name="PractiseCourse" table="practise_course">
<key column="pcourse_id" />
<property name="projectName" column="project_name" />
<property name="projectPeriod" column="project_period" />
</ joined-subclass>
<joined-subclass name="CertificationCourse" table="certification_course">
<key column="ccourse_id" />
<property name="certificationName" column="cert_name" />
<property name="examTime" column="exam_time"/>
</ joined-subclass>
</ class>
Inheritance-TPS
PractiseCourse pc = new PractiseCourse ();
pc.setName ( "web developer");
pc.setPeriod (300);
pc.setProjectName ( "Training System");
pc.setProjectPeriod (100);
session.save (pc);
TPH methods and their use is almost the same, load connected to inherit the use of outside-TPH
TPH under the parent category, generally speaking, only to create a form field in the table set up to distinguish between the type of object.
Different subclasses have different attributes stored in the same table, do not have to preserve the value of the property is empty.
Curriculum as an example, including the general courses, internship training courses and certification exams, and their relationship in Figure:
Inheritance-TPH
Inheritance-TPH
<class name="Course" table="course" discriminator-value="GC">
<id name="id" column="course_id">
<generator />
</ id>
<discriminator column="course_type" type="string" />
<property name="name" column="course_name" />
<property name="period" column="total_period" />
<property name="notes" />
<subclass name="PractiseCourse" discriminator-value="PC">
<property name="projectName" column="project_name" />
<property name="projectPeriod" column="project_period" />
</ subclass>
<subclass name="CertificationCourse" discriminator-value="CC">
<property name="certificationName" column="cert_name" />
<property name="examTime" column="exam_time"/>
</ subclass>
</ class>
Inheritance-TPH
PractiseCourse pc = new PractiseCourse ();
Course gc = new Course ();
CertificationCourse cc = new CertificationCourse ();
Course gcc = new CertificationCourse ();
session.save (pc);
session.save (gc);
session.save (cc);
session.save (gcc);
Inheritance-TPH
List gc = session.createQuery ( "from Course"). List ();
List pc = session.createQuery ( "from PractiseCourse"). List ();
List cc = session.createQuery ( "from CertificationCourse"). List ();
Iterator itg = gc.iterator ();
Iterator itp = pc.iterator ();
Iterator itc = cc.iterator ();
while (itg.hasNext ()) (
Course c = (Course) itg.next ();
System.out.println (c.getName ());
)
Relationship in the database design of a modeling method commonly used is the entity relationship model entity is independent of the existence of the real world things, such as students, teachers; computers, users, etc., which is reflected in the database one by one entity relationship table include things that reflect the characteristics of the property, and its reflection in the database table fields that relations between entities, such as students and teachers is a many-to-many relationship between the computer and the user is one-to-one relationship between the entities the relationship between not fixed, it depends entirely on demand, for example, between computers and users may also be a correlation between one-to-many relationship primarily as follows:
1, one-on-one relationship between the
2, one-to-many relationship
3, many-to-one relationship between the
4, in addition to many-to-many relationship many-to-many relationship table to reflect the needs of the relationship, the other is directly through the foreign key relationship to be embodied in the direction of
Is the direction of the relationship, the relationship is one-way from the entity A can be associated with another entity B, but B can not be physical entities A
For example, if teachers and courses is one-to-many relationship, and through a teacher to know all about his courses, but courses can not be aware of classroom teachers, this relationship is the relationship between the two-way one-way from the relations a role can be any other entity
Hibernate in the way the definition of the relationship between
Hibernate relationship defined as follows:
1, related party holders of related objects, usually kept in the attribute object.
2, in the mapping file, the use of one-to-one, one-to-many, many-to-one, many-to-many relationship between the definition of mapping.
3, for the one-to-many, many-to-many need to use the collection holders.
One-on-one relationship between the one-on-one relationship between the three ways:
The first is achieved through the foreign key that holds the current object of the association foreign key object;
The second is achieved through the primary key, that is, the current object that is the primary key is the primary key foreign key, that is the primary key of the current object and the object associated with the primary key is the same.
Third, to achieve through the relationship between the table, that is related to both sides of the form other than the key stored in the relationship between the table, through one-on-one relationship between the tables to reflect the relationship between the rarely used this way, one-on-one relationship - the way the foreign key
<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
<many-to-one name = "address"
column = "addressId"
unique = "true"
not-null = "true" />
</ class>
<class name="Address">
<id name="id" column="addressId">
<generator/>
</ id>
</ class>
One-on-one relationship - the foreign key in the association if the other side to hold the object, it should be written:
<class name="Address">
<id name="id" column="addressId">
<generator/>
</ id>
<one-to-one name="owner" property-ref="addressId"/>
</ class>
property-ref object reference to the definition of foreign key attributes is one-to-one relationship - the primary key way
<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
</ class>
<class name="Address">
<id name="id" column="personId">
<generator>
<param name="property"> person </ param>
</ generator>
</ id>
<one-to-one name="person" constrained="true"/>
</ class>
One-on-one relationship - the primary key, if the definition of a two-way one-on-one way, then
<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
<one-to-one name="address"/>
</ class>
<class name="Address">
<id name="id" column="personId">
<generator>
<param name="property"> person </ param>
</ generator>
</ id>
<one-to-one name="person" constrained="true"/>
</ class>
Many-to-one relationship between the many-to-one relationship, the current holder of foreign key objects. Through the holder of the corresponding foreign key to find the target. Thus, in many-to-one relationship, the current object contains an associated object, the object in order to attribute the existence of the object.
For example, the unit (Unit) and buildings (Buiding) is many-to-one relationship between. One block may include a number of modules, corresponding to a floor unit only

Many-to-one relationship between the many-to-one relationship between the

<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
<many-to-one name = "address"
column = "addressId"
not-null = "true" />
</ class>
<class name="Address">
<id name="id" column="addressId">
<generator/>
</ id>
</ class>

One-to-many relationship between the one-to-many association in the system is very common, one-to-many association is divided into one-way one-to-many two-way one-to-many.
One-to-many relationship between one-way only "one" side needs to configure two-way one-to-many configuration of both sides.
One-to-many relationship between the one-to-many relationship between the two ways to achieve:
The first is achieved through foreign keys, "one" does not hold the role of foreign keys, foreign keys are held by more than one party. Hibernate does not encourage the use of in this way to achieve one-to-many relationship.
The second is to achieve through the relationship table, foreign key relationship between the tables were held, each relationship must be registered in the relations table.
One-to-many relationships - the way the foreign key
<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
<set name="addresses">
<key column = "personId"
not-null = "true" />
<one-to-many/>
</ set>
</ class>
<class name="Address">
<id name="id" column="addressId">
<generator/>
</ id>
</ class>
One-to-many two-way - the way the foreign key
<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
<set name="addresses">
<key column = "personId"
not-null = "true" />
<one-to-many/>
</ set>
</ class>
<class name="Address">
<id name="id" column="addressId">
<generator/>
</ id>
<many-to-one name="person" column="personId"/>
</ class>
One-to-many relationships - the relationship between form
<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
<set name="addresses" table="PersonAddress">
<key column="personId"/>
<many-to-many column = "addressId"
unique = "true"
class = "Address" />
</ set>
</ class>
<class name="Address">
<id name="id" column="addressId">
<generator/>
</ id>
</ class>
One-to-many two-way - the relationship between form
<class name="Person">
<id name="id" column="personId">
<generator/>
</ id>
<set name = "addresses"
table = "PersonAddress">
<key column="personId"/>
<many-to-many column = "addressId"
unique = "true"
/>
</ set>
</ class>
Many-to-many relationship between the many-to-many relationship can only be resolved through the realization of the form, each relationship must be registered in the relations table.
The relationship between the two sides do not hold foreign keys, but all have a collection of attributes associated with the relationship between the representative of another role.

One-to-many one-way one-to-many association:
For one-to-many relationships can be used java.util.Set, or net.sf.hibernate.collection.Bag, type of Collection, in the XML mapping document is <set> </ set> or <bag> </ bag>
The realization of a one-way one-to-many relatively simple, but there is a problem, because it is a one-way link, in order to maintain a relationship, we can only control on the passive side cascade update. Related parties if the associated field is not null, when the Hibernate to create or update the relationship, the potential for illegal restraint.
One-to-many association one-to-many relationship between the emergence of a two-way solved the problem. In addition to bound it to avoid the unauthorized and the benefits of improved performance, there are other advantages: the establishment of a two-way connection can be associated either party to visit the other association has provided a more flexible means of control, a two-way one-to-many association multi-link:
Two-way one-to-many association is actually a combination of one-to-many and many-to-one.
Inverse = true a lot of configuration, control the direction of inversion
Inverse = false prosecution of a party-based many-to-many association many-to-many association is rather special, with one-to-many, one-to-one correlation is different from the needs of the middle table with complete information on the preservation of many-to-many mapping.
As a result of the middle table, so poor performance, to avoid large-scale use. Depending on the situation, take the lazy loading mechanism to avoid the overhead.
Hibernate data retrieval
Criteria Query
DetachedCriteria
HQL
Criteria Query
Criteria Query of the adoption of object-oriented design, data query for an object package.
Simply put, Criteria Query traditional SQL can be seen as a representation of the object, such as:
Criteria criteria = session.createCriteria (Tuser.class);
Criteria.add (Expression.eq ( "name", "Erica"));
Criteria.add (Expression.eq ( "sex", new Integer (1)));
Equivalent to: select * from t_user where name = 'Erica' and sex = 1
DetachedCriteria Query
Hibernate2 in, Criteria at the life cycle of the life cycle of session, that is, criteria difficult to reuse the object, Hibernate3 provides a new realization: DetachedCriteria
DetachedCriteria examples can exist independently from the session.
DetachedCriteria
deCriteria = DetachedCriteria.forClass (Tuser.class);
DeCriteria.add (Expression.eq ( "name", "Erica"));
....
Criteria criteria = deCriteria.getExecutableCriteria (session);
HQL
Criteria object as a mode of inquiry packages, is ideal for programmers. Hibernate in the realization of the process, however, the more concentrated in the HQL query language, so the function of Criteria There are a lack of time. The actual development, the most commonly used or recommended by the official inquiry Hibernate mode Package: HQL
HQL and Criteria is not one or the other, mutual isolation technology, the two can complement each other in the system development can be appropriate with the use of these two technologies.
HQL
HQL provides a more rich and flexible features, covering all the features of Criteria provide a more powerful query capabilities.
HQL provides a more traditional query syntax of SQL statements, but also provides a more comprehensive features.
HQL syntax is as follows
[select / update / delete ...] [from ...] [where ...] [group by [having ...]] [order by ...]
HQL-based SQL, while providing a more object-oriented package.
Practical technology HQL query entity entity attribute update and delete query packet with the sort parameter query bound queries reference data loading subquery
SQL query
HQL practical techniques - entity query
HQL clause case itself had nothing to do, but emerging category and attribute names as necessary to distinguish between the main case:
String hql = "from TUser"
Query query = session.createQuery (hql)
List userList = query.list ();
Tuser statement identified above and sub-category of all records.
If you write from Object, is found in the database table of all records in all tables.
Where conditions can be added, basically the same style of writing SQL
HQL practical skills - attributes inquiries sometimes we do not need to obtain a complete entity object, such as the name of the user may just want to be as follows:
List list = session.createQuery ( "select user, name from Tuser user"). List ();
Iteration on the list directly, each element is String
Can also get a number of attributes, such as select user, name, user, age from Tuser as user
List of return can be iterative, each element is the Object []
HQL practical technology - an array of attributes to return to the way query complex object-oriented style, can be dynamically constructed in the HQL object encapsulation.
CreateQuery ( "select new Tuser (user, name, user.age) from Tuser as user"). List ()
At this time to return to the List, iteration, each element object for TUSer through dynamic structure HQL object instance, we achieved the target of the query results of package. Note that the results of inquiries in addition to Tuser been assigned by the attribute, other attributes are not assigned.
The Select clause in HQL can be used in statistical functions, such as count (*), can also use the data function, such as the Upper (user.name). Can also be used distinct
HQL practical technology - update and delete entities
Hibernate2 in, HQL query only to update as follows:
Tuser user = (TUser) session.get (Tuser.class, new Integer (1))
User.setAge (new Integer (18))
Session.save (user)
If the volume changes very troublesome.
HQL practical technology - update and delete entities
Hibernate3 in:
Query query = session.createQuery ( "update Tuser set age = 18 where")
Query.executeUpdate ();
Delete:
Query query = session.createQuery ( "delete Tuser where age> 18")
Query.executeUpdate ();
Need to pay attention to is: the use of HQL delete / update clause, the attention to the impact of cache strategy.
HQL practical skills - grouping and sorting with SQL similar, HQL can be used to sort order by can also be used for the Group by, and having sub-groups after the operation, each data package in the array.
HQL practical technology - parameter binding statement in HQL query parameters directly spelling. But the messy code in this way, poor readability, performance low, the additional risk (SQL Injection)
Parameters can be bound to resolve
session.find method (Hibernate2)
session.find ( "from Tuser where name =?"," Erica", Hibernate.STRING)
Multi-parameter with an array of the realization of the situation.
HQL practical skills - the binding parameters can be filled with Query interface parameters:
Query query = session.createQuery ( "from Tuser user where user.name =? And user.age >?");
Query.setString (0, "Erica");
Query.setInteger (1,20);
HQL practical skills - in addition to the order of binding parameters outside placeholder, Hibernate also supports the invocation placeholder
Query query = session.createQuery ( "from Tuser where name: = name")
Query.setParameter ( "name", "Erica")

JavaBean package can also use query parameters
class UserQuery (
private String name;
private Integer age;
getter / setter
)
String hql = "from Tuser where name: = name and age: = age"
query = session.createQuery (hql)
userQuery uq = new UserQuery ();
uq.setName (..);
uq.setAge (...);
query.setProperties (up)
Iterator it = query.iterate ()

HQL practical techniques - reference inquiries
Hibernate can be configured to provide the HQL of the built-in support.
Mapping in the entity, through the definition of query-node query through session.getNamedQuery (...) method to obtain Query
HQL practical skills - a joint inquiry, subquery
Hibernate supports multi-table queries, and SQL sub-query syntax similar to
HQL practical technology - Data loaded in the traditional JDBC operation, we usually through SQL statements needed to load data processing, when the SQL submitted, these data have been read on the stand.
World in Hibernate, we have more choices (for related data)
HQL practical technology - real-time loading data loading (Immediate Loading)
When the entity to load soon after the completion of its associated data to load.
Lazy (Lazy Loading)
Physical load, the associated data are not immediate access, but the first time when the associated data is accessed again to read pre-loaded (Eager Loading)
Entities and the associated object at the same time to read, which is similar to real-time load. However, entities and their associated data through a SQL statement (based on external connection) at the same time read the bulk load (Batch Loading)
For immediate loading and delayed loading, bulk loading methods can be used to optimize performance.
HQL practical technology - real-time loading data loading (Immediate Loading)
<set… lazy="false">
Session.find method implementation, Hibernate to connect two SQL, respectively Tuser and Taddress loaded object. This is the basic principle of real-time load, when the host entity (related themes) loading, Hibernate will automatically read the associated data and associated attributes to complete filling
HQL practical skills - the way data is loaded lazy loading:
Real-time load, the load at the same time Tuser object, that is loaded at the same time it Taddress associated object. This has led to depletion of the following properties: Tuser object to read data, do not address information, read the address at the same time to pay the performance cost data.
Lazy loading is to solve the problem.
<set… lazy=true>
Genuine need in the Address associated only load Address
HQL practical skills - the way data is loaded in one-on-one pre-loaded case, we have used. Pre-loaded by outer-join to complete the loading of related data, so that through a SQL statement and its associated entities to complete the data read operation, the relative real-time or even read certain sections of the two SQL, no doubt, this kinds of mechanisms in the performance enhancement brought more.
However, for the collection of types, (that is, one-to-many, many-to-one, or many-to-many relationship), we do not recommend the use of pre-load means the same grounds with the real-time load for the collection, as long as allowed, as far as possible use lazy loading, to avoid performance loss.
HQL practical skills - the way to load pre-load data in exceptional circumstances, in particular for the complex relationship, such as multi-link, Hibernate generated Outer-JoinSQL might be too complicated at this time, we should be judged in accordance with pre-loaded in the At that time, the availability of the environment. At the same time, also can be adjusted hibernate.max-fetch-depth limited to the level of outer-join is generally set to 5 layers
HQL practical skills - the way to load bulk data load:
Bulk loading, is presented through a number of limited-volume conditions, a complete reading of multiple data.
Forms for the following SQL:
select * from T_User where
select * from T_User where
Can be synthesized:
select * from T_User where
HQL practical skills - the way data is loaded this is the so-called bulk loading mechanism, if you use a bulk loading mechanism, Hibernate query operation in the data before the current session will automatically look for any other type of data to be loaded and, if so, will the conditions of the merger in the current select statement to be submitted, so that a single database operation to read a number of tasks completed.
Physical configuration, can be batch-size bulk loading mechanism to open and load limit the number of each batch
<class name="TUser" table="T_User" batch-size="5">
batch-size should be set to a reasonable value (<10)
Entity object life cycle of a persistent classes may be in three different instances of a certain kind of state:
Transient (transient)
Persistent (persistent)
Trust (detached)
Transient (transient)
The example has never been with any persistence context have been associated.
It does not have persistent identity (primary key value equivalent).
Persistent (persistent)
Examples of current with a persistence context associated.
It has a persistent identity (primary key value equivalent), and may in the database have a corresponding line.
For a particular persistence context, Hibernate persistence to ensure that logos and Java logo (its value on behalf of the target location in memory) equivalent.
Trust (detached)
Examples have been with a persistence context associated happened, but that context was closed, or is this an example of sequence (serialize) to another process.
It has a persistent identity, and may be in the database, there is a corresponding line.
Trust status for example, Hibernate can not guarantee that any persistent identity and the relationship between the Java logo.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Hibernate Quick Start

  • An essential reference resource list of Java

    Since the Java platform since 1995 as a whole began to introduce programming community, and its development has gone far beyond the early Java experts and those who promote the idea of "applet ubiquitous" of that vision. In contrast, Java emerge

  • Pring Beanfactory at the jsp, servlet, web.xml and other configuration

    Keywords: spring beanfactory Spring in the web application called the Beanfactory 1) Configure web.xml Java code <? xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE web-app PUBLIC "- / / Sun Microsystems, Inc. / / ...

  • ActiveMQ practice the road (four) ActiveMQ 4.x + JBoss 4.x MDP actual articles

    Keyword: ActiveMQ ActiveMQ practice the road (four) ActiveMQ 4.x + JBoss 4.x MDP actual articles At <<ActiveMQ Practice ( Three ) ActiveMQ 4.x +JBoss 4.x Consolidating articles >> which we compare in detail the ActiveMQ with JBoss integration

  • ROR resources

    Ruby Web site resources: ruby official website: http://www.ruby-lang.org ruby doc official website: http://www.ruby-doc.org rubyonrails official website: http://www.rubyonrails.org programming ruby online edition (Ruby studying the "Bible") ...

  • What is the JPA

    Same, JDO, also started compatible JPA. At the field of ORM, it seems that JPA is a benevolent government, is the normative specification. At the support of major manufacturers, JPA use became widespread. 2 Spring Spring + Hibernate often referred to as t

  • J2EE Architect road

    J2EE Architect road Looking casual, working into the fifth year, the discovery came from the Java programmer to architect J2EE course. Found that computer to install a wide range of J2EE tools: JBuilder, WSAD, Eclipse, Rose, Together, Weblogic, Jtest, Opt

  • Hibernate Inteceptor

    The end of the project stage, the client suddenly put forward a very troublesome but normal demand, the system records all changes must be carried out. Formats such as: 2004.1.1 12:30 Ikuya wind orders Sales Order Date 2004.1.2-> 2004.1.3 The firs ...

  • jboss ejb3 Message Driven Bean

    Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri

  • FLEX: integrating Spring + Hibernate

    Before a friend also wanted to study development of FLEX. Asked me to help him to be a small sample. Spent a weekend time, to integrate a sampleproject. Client: FLEX Server: Spring2.5 + Hibernate3.2 + Hibernate-annotations3.3.1 + MySQL5 FDS: BlazeDS3 IDE:

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries