Beruflich Dokumente
Kultur Dokumente
0
Introduction............................................................ ..................................2
Architecture.................................................... ..........................................3
Example:....................................................... ........................................3
Hibernate Query Language....................................................................... ..10
Understanding HQL Syntax................................................................... ...10
Clauses in the HQL are:................................... ....................................11
Aggregate functions are:.......................................................... ............11
Subqueries.................................................................................... .....11
HQL from clause............................................... ..................................11
Hibernate Select Clause....................................... ................................11
Hibernate Criteria Query Example..................................... ..........................11
Hibernate & JNDI.................................................................................. ....12
Hibernate Datasource Properties.................................... ..........................13
Using Stored Procedures in Hibernate......................................... .................14
Rules/limitations for using stored procedures.............................................15
Mapping SQL and Java data types........................................... ....................15
J2EE & Hibernate.............................................................................. ........16
Transaction strategy configuration...................................... ......................16
Table : JTA TransactionManagers...................................... ........................16
Association Mappings..................................................... ...........................18
One to one................................................ ...........................................18
Scenario:............................................................................. ..............18
Schema:.................................................................................. ..........18
Many to one................................................................................ ..........19
Scenario:............................................................................. ..............19
Hibernate Mapping:............................................................. ................19
Schema:.................................................................................. ..........19
One to many........................................................................ .................19
Scenario:............................................................................. ..............19
Hibernate Mapping:............................................................. ................19
Schema:.................................................................................. ..........20
Collections of values.......................................... .......................................20
Collection Elements.................................................................... ............20
Set.............................................................. .....................................21
Array................................................................................................ .21
Map................................................................ ..................................21
List....................................................................... ............................21
Hibernate object states.................................... .........................................22
Modifying persistent objects...................................... ..............................22
Modifying detached objects.................................... .................................23
Introduction
Example:
Here is an example of using hibernate . But before that we need to download
the hibernate related files from hibernate.org and unzip them. Following jar
files are important and should be included with our application :
Step 1: Create a table as :
Step 2: Now write a persistent object or POJO (Plain Old Java Object)
Step 3: Now write a mapping file ;this is nothing but an xml file .
<hibernate-mapping>
<class name="Employee" table="EMP">
<id name="id" column="EMPNO" type="java.lang.Integer">
<generator class="sequence"/>
</id>
<property name="empName" type="java.lang.String" column="ENAME"/>
<property name="empJob" type="java.lang.String" column="JOB"/>
</class>
</hibernate-mapping>
Points to remember about the mapping file :-
Generator Description
It generates identifiers of type long, short or int that are unique only when
Increment no other process is inserting data into the same table. It should not the
used in the clustered environment.
native It picks identity, sequence or hilo depending upon the capabilities of the
underlying database.
lets the application to assign an identifier to the object before save() is
assigned
called. This is the default strategy if no <generator> element is specified.
Save the above file as Employee.hbm.xml.It's a good practise to give the name of your mapping
file similar to the persistant class name.
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@pc176:1521:OBODB</property>
<property name="connection.username">obo1</property>
<property name="connection.password">obopass1</property>
</session-factory>
</hibernate-configuration>
Save file as hibernate.cfg.cml.
In the above configuration file The dialect property is org.hibernate.dialect. OracleDialect which
tells the Hibernate that we are using Oracle Database. Hibernate supports many database and
provides dialect support for each. Few of them are.
● DB2 - org.hibernate.dialect.DB2Dialect
● MySQL - org.hibernate.dialect.MySQLDialect
● Oracle (any version) - org.hibernate.dialect.OracleDialect
● Oracle 9 - org.hibernate.dialect.Oracle9Dialect
● Sybase - org.hibernate.dialect.SybaseDialect
● Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect
The <mapping resource="Employee.hbm.xml"/> property is the mapping for our contact table.
The hbm2ddl.auto option turns on automatic generation of database schemas - directly into the
database. This can of course also be turned off (by removing the config option) or redirected to a
file with the help of the SchemaExport Ant task.
//Create new instance of Employee and set values in it by reading them from form object
System.out.println("Inserting Record");
Employee emp = new Emp();
emp.setId(640);
emp.setEmpName("ABC");
emp.setEmpJob("XYZ");
session.save(emp);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual emp insertion will happen at this step
session.flush();
session.close();
}
}
}
We have to startup Hibernate. This startup includes building a global SessionFactory object and to
store it somewhere for easy access in application code. A SessionFactory can open up new
Session's. A Session represents a single-threaded unit of work, the SessionFactory is a thread-
safe global object, instantiated once.
A SessionFactory is threadsafe, many threads can access it concurrently and
request Sessions. A Session is a non-threadsafe object that represents a single unit-of-work with
the database. Sessions are opened from a SessionFactory and are closed when all work is
completed.
Subqueries
Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the
underlying database supports it.
Note : We have to specify the field name and the persistant class name with the SELECT clause.
Similarly we can apply WHERE,ORDER BY,GROUP BY clause.
For use inside an application server, we should almost always configure Hibernate to obtain
connections from an application server Datasource registered in JNDI. We need to set at least one
of the following properties:
Hibernate Datasource Properties
Propery name Purpose
connection.datasource datasource JNDI name
Jndi.url URL of the JNDI provider (optional)
Jndi.class class of the JNDI InitialContextFactory
(optional)
<hibernate-configuration>
<session-factory>
<property name="jndi.url">t3://localhost:7080</property>
<property name="jndi.class">weblogic.jndi.WLInitialContextFactory</property>
<property name="connection.datasource">jdbc/obodb_NonXA_ds</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Mapping file:
<hibernate-mapping>
<class name="Employee" table="EMP">
<id name="id" column="EMPNO" type="java.lang.Integer">
<generator class="sequence"/>
</id>
<property name="empName" type="java.lang.String" column="ENAME"/>
<property name="empJob" type="java.lang.String" column="JOB"/>
</class>
<sql-query name="selectAllEmployees_SP" callable="true">
<return alias="emp" class="Employee">
<return-property name="id" column="EMPNO"/>
<return-property name="empName" column="ENAME"/>
<return-property name="empJob" column="JOB"/>
</return>
{ ? = call selectAllEmployee() }
</sql-query>
</hibernate-mapping>
stored procedures currently only return scalars and entities. <return-join> and <load-collection>
are not supported.
Oracle rule:
• The procedure must return a result set. This is done by returning a SYS_REFCURSOR in Oracle 9
or 10. In Oracle we need to define a REF CURSOR type.
• Recommended form is { ? = call procName(<parameters>) } or { ? = call procName } (This is
more an Oracle rule than a Hibernate rule.)
To use Stored Procedures with Hibernate we need to create a stored procedure first and then
specify <sql-query> name inside the mapping file and call the procedure from mapping file and to
use this query in our application use session.getNamedQuery(<sql-query name>).
CHARACTER String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BINARY byte[]
VARBINARY byte[]
LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
<hibernate-configuration>
<session-factory>
<property name="jndi.url">t3://localhost:7001</property>
<property name="jndi.class">weblogic.jndi.WLInitialContextFactory</property>
<property name="connection.datasource">jdbc/obodb_NonXA_ds</property>
<property
name="transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prope
rty>
<property
name="transaction.manager_lookup_class">org.hibernate.transaction.WeblogicTransaction
ManagerLookup</property>
</hibernate-configuration>
Association Mappings
One to one
In this association one class holds a reference to a single instance of another class and they are
related by a common PK.
Scenario:
Hibernate Mapping:
In Hibernate, this could be mapped as follows:
Schema:
Foo
Id
Bar
Id
Many to one
A many-to-one reference is analogous to a simple Java reference. It is the same as the one-to-
one situation except there is no requirement to have a shared PK. Instead a FK is used.
Scenario:
Bar Foo.getBar() // returns corresponding Bar instance
Hibernate Mapping:
<class name="Foo" table="foo">
...
<many-to-one name="bar" class="Bar" column="bar_id"/>
</class>
Schema:
Foo
Id
Bar Bar_id
Id
One to many
A one-to-many reference is basically a collection. Here a class, A, holds a reference to a collection
of another class, B. The reverse of it results into Many to one association.
Scenario:
Set Foo.getBars() // returns corresponding Bar instance
Hibernate Mapping:
<class name="Foo" table="foo">
...
<set role="bars" table="bar">
<key column="foo_id"/>
<one-to-many class="Bar"/>
</set>
</class>
Schema:
Foo
Id
Bar
Id foo_id
Collections of values
Any collection of values or many-to-many association requires a dedicated collection table with a
foreign key column or columns, collection element column or columns and possibly an index
column or columns.
For a collection of values, we use the <element> tag inside appropriate collection node.
<element
column="column_name" (1)
formula="any SQL expression" (2)
type="typename" (3)
length="L"
precision="P"
scale="S"
not-null="true|false"
unique="true|false"
node="element-name"
/>
(1) column (optional): The name of the column holding the collection element values.
(2) formula (optional): An SQL formula used to evaluate the element.
(3) type (required): The type of the collection element.
Collection Elements
Set
<set name="names" table="person_names">
<key column="person_id"/>
<element column="person_name" type="string"/>
</set>
Array
An array of entities - in this case, a many to many association:
<array name="addresses"
table="PersonAddress"
cascade="persist">
<key column="personId"/>
<list-index column="sortOrder"/>
<many-to-many column="addressId" class="Address"/>
</array>
Map
A map from string indices to dates:
<map name="holidays"
table="holidays"
schema="dbo"
order-by="hol_name asc">
<key column="id"/>
<map-key column="hol_name" type="string"/>
<element column="hol_date" type="date"/>
</map>
List
A list of components (discussed in the next chapter):
<list name="carComponents"
table="CarComponents">
<key column="carId"/>
<list-index column="sortOrder"/>
<composite-element class="CarComponent">
<property name="price"/>
<property name="type"/>
<property name="serialNumber" column="serialNum"/>
</composite-element>
</list>
• Transient - an object is transient if it has just been instantiated using the new operator, and it is
not associated with a Hibernate Session. It has no persistent representation in the database and
no identifier value has been assigned. Transient instances will be destroyed by the garbage
collector if the application doesn't hold a reference anymore. Use the Hibernate Session to make
an object persistent (and let Hibernate take care of the SQL statements that need to be executed
for this transition).
• Persistent - a persistent instance has a representation in the database and an identifier value. It
might just have been saved or loaded, however, it is by definition in the scope of a Session.
Hibernate will detect any changes made to an object in persistent state and synchronize the state
with the database when the unit of work completes. Developers don't execute manual UPDATE
statements, or DELETE statements when an object should be made transient.
• Detached - a detached instance is an object that has been persistent, but its Session has been
closed. The reference to the object is still valid, of course, and the detached instance might even
be modified in this state. A detached instance can be reattached to a new Session at a later point
in time, making it (and all the modifications) persistent again. This feature enables a
programming model for long running units of work that require user think-time. We call them
application transactions, i.e. a unit of work from the point of view of the user.
Sometimes this programming model is inefficient since it would require both an SQL SELECT (to
load an object)
and an SQL UPDATE (to persist its updated state) in the same session. Therefore Hibernate offers
an alternate
approach, using detached instances.
Hibernate supports this model by providing for reattachment of detached instances using the
Session.
update() or Session.merge() methods:
If the Cat with identifier catId had already been loaded by secondSession when the application
tried to reattach it, an exception would have been thrown.Use update() if we are sure that the
session does not contain an already persistent instance with the same identifier, and merge() if we
want to merge our modifications at any time without consideration of the state of the session. In
other words, update() is usually the first method we would call in a fresh session, ensuring that
reattachment of our detached instances is the first operation that is executed.