explain JSF framework compare with the Struts framework

Struts framework  versus JavaServer Faces

  • Matured since Struts has been around for a few years.
It has got several successful implementations.
JSF is in its early access release and as a result somewhat
immature.

  • The heart of Struts framework is the Controller, which
uses the Front Controller design pattern and the
Command design pattern. Struts framework has got
only single event handler for the HTTP request.
The heart of JSF framework is the Page Controller Pattern where
there is a front controller servlet where all the faces request go
through with the UI components and then fire off events for each
component and render the components using a render toolkit. So
JSF can have several event handlers on a page. Also JSF
loosely couples your model, where it can hook into your model (i.e
unlike Struts your model does not have to extend JSF classes).

  • Struts does not have the vision of Rapid Application
Development (RAD).
JSF was built with a component model in mind to allow RAD. JSF
can be thought of as a combination of Struts framework for thin
clients and the Java Swing user interface framework for thick
clients.
Has got flexible page navigation using navigation rules
inside the struts-config.xml file and Action classes
using maoping.findForward(…) .
JSF allows for more flexible navigation and a better design
because the navigation rule (specified in faces-config.xml ) is
decoupled from the Action whereas Struts forces you to hook
navigation into your Action classes.
  • Struts is a sturdy frame work which is extensible and
flexible. The existing Struts applications can be
migrated to use JSF component tags instead of the
original Struts HTML tags because Struts tags are
superseded and also not undergoing any active
development. You can also use the Struts-Faces
Integration library to migrate your pages one page at
a time to using JSF component tags.
JSF is more flexible than Struts because it was able to learn from
Struts and also extensible and can integrate with RAD tools etc.
So JSF will be a good choice for new applications.?

Table-Per-Class Hierarchy Mapping in hibernate

In our first mapping example, we’ll create a mapping document for the three classes that stores objects
of the hierarchy in a single table structure. The mapping is shown in Listing 5.20.
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="example.products">
<classname="CD"
table="cd"
discriminator-value="cd">
<id name="id"
type="integer"
unsaved-value="0">
<generator class="hilo"/>
</id>
<discriminator column="cd_type"
type= "string"/>
<property name="title"/>
<property name="artist"/>
<property name="purchasedate" type="date"/>
<property name="cost" type="double"/>
<subclass name="SpecialEditionCD"
discriminator-value="SpecialEditionCD">
<property name="newfeatures" type="string"/>
</subclass>
<subclass name="InternationalCD"
discriminator-value="InternationalCD">
<property name="languages"/>
<property name="region"/>
</subclass>
</class>
</hibernate-mapping>
Listing 5.20
The mapping in Listing 5.20 is more complex than the mappings you’ve seen so far. The first addition in
the mapping is the <discriminator> element. To understand how the mapping works, consider what
Hibernate will attempt to accomplish with the hierarchy objects: When the user instantiates and saves a
CD object, it’s saved to a table called CD with the appropriate attributes from the CD class mapped to the
database columns. When the user instantiates and saves a SpecialEditionCD object, it’s saved to the
same CD table as the CD object. The difference is that additional attributes are mapped from the
SpecialEditionCD. Those additional attributes are set to null for the CD object. To differentiate
between the three classes in the hierarchy, we add a discriminator column to the table and enter a spe-cific
value in the column for each object type.
The <discriminator> element includes two attributes in our example. The first attribute, column,
relates to the column in the database to be used for the discriminator value. The second attribute, type,
determines the column type.
In the <class> element, an element called <discriminator-value> relates to the value to be
placed in the discriminator column for an object instantiated from the CD class. Figure 5.1 shows all of
the rows in the cd table.
Figure 5.1
The database schema for this mapping is:
create table cd(
id int,
title text,
artist text,
purchasedate datetime,
cost double,
newfeatures text,
languages text,
region int,
cd_type text
);
Notice that the database schema consists of a single table and columns for all the possible attributes in
the base CD class as well as the child SpecialEditionCD and InternationalCD classes. By using the
table-per-class method, we need only one table for all object types in the mapped hierarchy.
Hibernate can do this by using the discriminator column, defined as cd_type in the schema, to hold a
string value indicating the class of object held in a particular row.
Here’s the code for an example use of the CD hierarchy. We used this code to produce the database rows
illustrated earlier:
import java.io.*;
import java.util.*;
import net. sf.hibernate.*;
import net. sf.hibernate.cfg.*;
import example.products.CD;
import example.products.SpecialEditionCD;
import example.products.InternationalCD;
public class CDTest {
public static void main(String [] args) {
try {
Session session = HibernateSession.currentSession();
CD cd = new CD("Grace Under Pressure", "Rush", new Date(), 9.99);
SpecialEditionCD secd = new SpecialEditionCD
("Grace Under Pressure", "Rush", new Date(), 9.99, "Widescreen");
InternationalCD icd = new InternationalCD
("Grace Under Pressure", "Rush", new Date(), 9.99, "Spanish", 4);
session.save(cd);
session.save(secd);
session.save(icd);
session.flush();
session.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
We create three different objects, one for each class type, and persist them to permanent storage.
Hibernate puts the appropriate column values in the rows, depending on the class type.

Creating Persistent Java Classes in Hibernate

The entire work of Hibernate is encapsulated in its ability to take the values from Java class
attributes and persist them to a database table. the mapping docu-ment
is key in determining how Hibernate pulls the values from the classes. Unless Hibernate is
changed from its default behavior, it uses reflection to determine how to access the attributes of
the Java class. As a developer of the Java class, it’s your responsibility to create the class in a con-sistent
manner.
You need to follow some simple guidelines when developing Java classes:
❑Hibernate will only persist attributes specified in the mapping document; therefore you
can include in your class as many temporary attributes as needed. If the temporary
attributes aren’t persisted, their values will be lost when the object is loaded from perma-nent
storage in the future.
❑All attributes that will be persisted should be declared private and have setter/getting
methods defined in the JavaBean style. For example:
private String firstname;
public String getFirstname() {
return firstname;
}
public void setFirstname(String s) {
firstname = s;
}
Note that the setter/getter methods don’t need to be declared public, because Hibernate can
locate them using reflection even if they’re protected or private. Further, you can use a method
name like isFirstname() as well as set and get.
❑Hibernate can handle mapping from just about any data type. If you’re using Java primitives
and JDK types, use the type, and refer to the Hibernate types described in the Chapter 4 when
creating the mapping document.
❑If an attribute type is a collection like a Map, List, or Set, you’ll need to do additional work
when creating the mapping. For collections,
❑Mapped classes can use the concept of composition, where an attribute’s type is another class.
The last half of Chapter 6 discusses composition mapping also called components in Hibernate
in full detail.
❑All classes should contain an ID in order to allow easy identification of your objects within
Hibernate and the database. As you read in Chapter 4, IDs have values like int, long, or String.
Be sure to use the right type when defining your ID, especially if you’re using an ID generator.
❑Interfaces, final classes, and some inner classes can be mapped to permanent storage using
Hibernate. See later sections in this chapter for more information.
❑All Java classes that will be persisted need a default constructor.

Relationship Elements in hibernate

One of Java’s most widely used features is associating one class with another through composition or
some other means. For example, you might have an employee object that contains a social security
object. You need to be able to map these relationships in the database. In this section, we aren’t talking
about situations where you have a vector of another class as an attribute.
Hibernate’s mapping document uses two relationship elements: <many-to-one> and <one-to-one>. In
this section, we’ll describe the mappings;
<many-to-one> Element
In the course of object mapping, in some situations many objects associate to a single object. This is a
many-to-one relationship; you use the <many-to-one> element for the mapping. The format of the ele-ment
is as follows:
<many-to-one
name="string"
column="string"
class="string"
cascade=- [all] [none] [save-update] [delete]"
outer-join="[true] [false] [auto]"
update=" [true] [false]"
insert="[true] [false]"
property-ref="associated class" [optional]
access=" [field] [property] [component class name]"
/>
This element has the following attributes:
❑name: Specifies the name of the Java attribute associated with the relationship.
❑column: Specifies the name of the database column for the mapping. This is an optional
attribute; the default is the name attribute value.
❑class: Specifies the name of the class that is part of the relationship. Hibernate uses reflection if
this attribute isn’t included.
❑cascade: See the description in our discussion of the <hibernate-mapping> element.
❑outer-join: Determines whether an outer join should be used when pulling this object from the
database row. This attribute is optional; the default is auto. The possible values include auto,
true, and false. If the value is auto, an outer join is used if the related class isn’t using
a proxy.
❑update: Determines whether this specific attribute should be used in an UPDATE SQL query.
This is an optional attribute; the default is true.
❑insert: Determines whether this specific attribute should be used in an INSERT SQL query. This
is an optional attribute; the default is true. Note that if both the update and insert attributes
are false, then you must assume this attribute will be filled by another attribute or possibly by
a database trigger.
❑property-ref: In most relationships, the related class’s primary key is stored in this mapped col-umn.
In some databases, the relationship from the primary class to the related class isn’t based
on the primary key but on some other column. Since Hibernate attempts to use the identifier of
the related class, you need to specify the exact column to use. The property-ref attribute
specifies the exact column. (You’ll see an example in Chapter 5.)
❑access: See the description in our discussion of the <id> element.
<one-to-one> Element
In the course of object mapping, in some situations one object is associated with a single object. This is a
one-to-one relationship; you use the <one-to-one> element for the mapping. The format of the ele-ment
is as follows:
<one-to-one
name="name"
class="class"
cascade=" [all] [none] [save-update] [delete]"
[optional - default none] constrained=" [true] [false]"
outer-join=" [true] [false] [auto]"
property-ref="property other than primary key of mapped table"
[optional] access=" [field] [property] [component class name]"
/>
This element has the following attributes:
❑name: Specifies the name of the Java attribute associated with the relationship.
❑class: Specifies the name of the class that is part of the relationship. Hibernate uses reflection if
this attribute isn’t included.
❑cascade: See the description in our discussion of the <hibernate-mapping> element.
❑outer-join: Determines whether an outer join should be used when pulling this object from the
database row. This attribute is optional; the default is auto. The possible values include auto,
true, and false. If the value is auto, an outer join is used if the related class isn’t using a
proxy.
❑constrained: Determines that a foreign key constraint exists with the primary key of the
mapped table.
❑property-ref: In most relationships, the related class’s primary key is stored in this mapped col-umn.
In some databases, the relationship from the primary class to the related class isn’t based
on the primary key but on some other column. Since Hibernate attempts to use the identifier of
the related class, you need to specify the exact column to use. The property-ref attribute
specifies the exact column. (You’ll see an example in Chapter 5.)
❑access: See the description in our discussion of the <id> element.
<component> Element
The <component> element is designed to allow a property to be saved in the current object’s mapping
from another class. The format of the element is:
<component
name="name"
class="class"
update="true | false" [optional - defaults to true]
insert="true | false" [optional - defaults to true]
access="field | property | class" [optional - defaults to property]
<property/>
<many-to-one/>
/>
This element has the following attributes:
❑name: Specifies the name of the property to map.
❑class: Specifies the child class where the named property appears.
❑update: Determines whether this specific attribute should be used in an UPDATE SQL query.
This is an optional attribute; the default is true.
❑insert: Determines whether this specific attribute should be used in an INSERT SQL query. This
is an optional attribute; the default is true. Note that if both the update and insert attributes are
false, then you must assume this attribute is filled by another attribute or possibly by a
database trigger.
❑access: See the description in our discussion of the <id> element.
For all the properties in the child class that need to be mapped, you need to include <property> ele-ments.
You can also add appropriate relationships to the <component> element.
<subclass> Element
When an inheritance relationship is defined for your Java classes, the hierarchy needs to be defined.
Since Hibernate recommends the table-per-class-hierarchy mapping, you should define all subclasses
with the <subclass> element. Subclass definitions include attributes as well as the properties that have
been added to this specific subclass.
The format of the element is as follows:
<subclass
name=”name”
discriminator-value="value" [optional - defaults to name value]
proxy="interface" [optional]
lazy="true ( false" [optional]
dynamic-update="true | false"[optional - defaults to false]
dynamic-insert="true | false" [optional - defaults to false]
<property/>
/>
This element has the following attributes:
❑name: Specifies the name of the Java class this mapping document is designed to represent.
Hibernate expects a fully qualified class name in this attribute if you don’t have the package
attribute in the <hibernate-mapping> element.
❑discriminator-value: Specifies the value used to distinguish between different classes in an
inheritance hierarchy. The default is the class name.
❑proxy: Tells Hibernate whether to use lazy initialization for objects of this mapping type. Lazy
initialization allows Hibernate to basically stub out the data in an object. If you’re using lazy ini-tialization,
you create objects and load them just as in the example application in Chapter 3, but
Hibernate won’t populate or make a call to the database for data until the object is used. The
proxy attribute requires you to provide a class that is used for the lazy initialization; this should
normally be the class name used in the name attribute.
❑dynamic-update: If true, then when Hibernate updates a row in the database for a class
attribute that has changed, it generates an UPDATE SQL statement at runtime during the
update() method call on the session and only include the columns of the table that have been
updated. This is an optional attribute; the default is false.
❑dynamic-insert: The same as dynamic-update in principle; but Hibernate dynamically creates
an INSERT SQL statement with only those columns that aren’t null values. This is an optional
attribute; the default is false.
Once the attributes have been defined for the subclass, you need to define all the new attributes that
should be persisted. Use the <property> element to define each attribute.
<joined-subclass> Element
If you don’t want to use the recommended inheritance mapping, you can choose the table-per-subclass
mapping. Each subclass must have its own <joined-subclass> element. You include all
the usual elements like <property>, <key>, and so on for this subclass.
The format of the element is as follows:
<joined-subclass
name="name"
proxy="interface" [optional]
lazy="true | false" [optional]
dynamic-update="true | false" [optional - defaults to false]
dynamic-insert="true | false" [optional - defaults to false]

Building the Mapping Document in hibernate

Hibernate can’t persist Java objects without a mapping document for each
class that tells Hibernate how to store the information it finds in the objects. In this section, we’ll lay out
the full mapping document and all the elements available to you. Then, in  we’ll show how to
map from real Java classes to your database.
The format of the mapping document is:
<?xml version=" 1.0" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>
<hibernate-mapping>
</hibernate-mapping>
To give you a good handle on this document, we’ll run through all the available elements and how they
affect Hibernate when you’re mapping Java objects to a database. Some of these mappings are compli-cated,
such as relationships and collections. We’ll touch on the elements here so you have a good idea
how they work, and then we’ll devote chapters to more detailed discussions of the topic.
<hibernate-mapping> Element
The <hibernate-mapping> element is the root element for the mapping document. Its format is:
<hibernate-mapping
schema="name" [optional]
default-cascade="none I save-update" [optional - default none]
auto-import="true | false" [optional - default true]
package="name" [optional]
/>
This element has four available attributes:
❑package: Fully qualifies unqualified classes in the mapping document. As you’ll see later, the
<class> element includes a name attribute that relates to the name of the Java class being
mapped. You can choose to use the package attribute and fully qualify the Java class. For
example:
<hibernate-mapping package="com.company">
<class name="Account"/>
</hibernate-mapping>
In this example, we’re mapping the class com.company.Account. If we didn’t add the
package attribute to the element, the system would expect to map a class called Account.
❑schema: Like the package attribute, fully qualifies the table used in this particular mapping. If
you add the schema attribute, the supplied namespace is appended to the table. For example:
<hibernate-mapping schema="products">
<class table="CD"> </class>
</hibernate-mapping>
In this example, the fully qualified database/table is products.CD. The schema attribute is
optional.
❑default-cascade: Specifies how actions that are performed on a parent are cascaded to a child.
The parent/child relationship is created through one-to-one, many-to-many, or one-to-many
mappings. (We’ll discuss these mappings in detail in Chapter 5.) For each mapping, you can
specify a cascade attribute; if you don’t, the default-cascade attribute’s value is used.
There are four possible values for default-cascade: all, none, save-update, and
delete. (The meanings are self-explanatory.) If you don’t specify a default-cascade
attribute, the default is none (no cascading of options occurs).
❑auto-import: If set to false, doesn’t allow unqualified class names in query strings. When you
build queries using HQL, you specify the class name provided in the <class name= ""> ele-ment.
The default is true; this attribute is optional.
<class> Element
Since we’re building a mapping file between a class and a database table, we need to specify the class
this mapping document references. The <class> element is designed for this purpose:
<class
name="name"
table="table" discriminator-value="value" [optional]
mutable="true | false" [optional - defaults to true]
schema="name" [optional]
proxy="interface" [optional]
dynamic-update="true | false" [optional - defaults false]
dynamic-insert="true | false" [optional - defaults false]
select-before-update="true | false" [optional - defaults false]
polymorphism="implicit | explicit" [optional - defaults implicit]
where="string" [optional]
persister="class" [optional]
batch-size="#" [optional -defaults 1]
optimistic-lock=""none | version | dirty | all"
[optional - defaults version]
lazy="true | false" [optional]
/>
The element includes 15 attributes:
❑name: Specifies the name of the Java class this mapping document is designed to represent.
Hibernate expects a fully qualified class name in this attribute if you don’t include the package
attribute in the <hibernate-mapping> element.
❑table: Specifies the name of the table to be used when persisting the Java object for this map-ping.
❑discriminator-value: Distinguishes between different classes in an inheritance hierarchy. The
default is the class name.
❑mutable: Signals whether an object persisted by Hibernate can be updated/deleted. If this
attribute is set to false, then the object is essentially read-only. The object can be persisted by
Hibernate but never updated or deleted from permanent storage.
❑schema: Overrides the value for the schema attribute specified in the <hibernate-mapping>
root element (if such a value has been set).
❑proxy: Tells Hibernate whether to use lazy initialization for objects of this mapping type. Lazy
initialization lets Hibernate stub out the data in an object. If you’re using lazy initialization, you
create objects and load them just in the example application in Chapter 3; but Hibernate won’t
populate (make a call to the database for data) until the object is used. The proxy attribute
requires that you provide a class to be used for the lazy initialization; this should normally be
the class name used in the name attribute.
❑dynamic-update: If true, then when Hibernate updates a row in the database for a class
attribute that has changed, it generates an UPDATE SQL statement at runtime during the
update() method call on the session and only include the columns of the table that have been
updated. This is an optional attribute; the default is false.
❑dynamic-insert: The same as dynamic-update in principle; but Hibernate dynamically creates
an INSERT SQL statement with only those columns that aren’t null values. This is an optional
attribute; the default is false.
❑select-before-update: If true, Hibernate performs a select to determine if an update is needed
(by default, Hibernate won’t perform an update unless the object has been modified). This is an
optional attribute; the default is false.
❑polymorphism: Specifies whether to use implicit or explicit polymorphism. As you’ll see later
in this chapter and in Chapter 6, you can define mappings that specify a hierarchy of objects
based on inheritance between Java classes. When a query, usually a find(), is executed,
Hibernate returns instances of this class when the class name or superclass is named in the
query; this is implicit polymorphism. In explicit polymorphism, Hibernate returns instances of
the class and its mapped subclasses. This attribute is optional; the default is implicit.
❑where: Specifies a global where clause for this class mapping.
persister: Specifies the class that will be used to persist this particular class to the database.
❑batch-size: Specifies the total number of instances to pull when Hibernate pulls instances from
the database for this class. This attribute is optional; the default is 1.
❑optimistic-lock: Specifies the type of locking used for the row, table, or database when updates
need to occur in the database. The values available are:
❑none: No optimistic locking.
❑version: Checks the version or timestamp column.
❑dirty: Checks those columns that have been changed.
❑all: Checks all columns.
This attribute is optional; the default is version.
❑lazy: If true, assumes the proxy attribute is included and the proxy class name is the same as the
mapped class name.
<id> Element
When you’re mapping a Java class to a database table, an ID is required. The ID is the primary key col-umn
of the database table used to persist a specific Java object. In addition, you should define a
setter/getter pair of methods, with the Java class for the ID following the JavaBean style. The <id> ele-ment
specifies information about the ID column. The format of the <id> element is as follows:
<id
name="name" [optional]
type="type" [optional]
column="column" [optional - defaults to name value]
unsaved-value="ant | none | null | value" [optional - defaults to null]
access="field | property | class" [optional - defaults to property]
<generator/>
/>
<generator class="class"
<param/>
/>
The <id> element has five elements and one subelement:
❑name: Specifies the name of the ID. This is an optional attribute; it’s included in many map-pings
with a value of "id".
❑type: Specifies the Hibernate type for the ID. If a type isn’t provided, Hibernate uses reflection
to try to determine the type. For a list of the Hibernate types, see the later description of the
<property> element.
❑column: Specifies the name of the database column. This is an optional attribute; if it isn’t speci-fied,
the database column name is the value in the name attribute. You need to include either the
name or the column attribute in the <id> element.
unsaved-value: Determines whether a newly instantiated object needs to be persisted (as men-tioned
in Chapter 3). This is an optional attribute; the default is null.
❑access: Specifies the way Hibernate accesses an object’s attribute using traditional JavaBean
style setter/getter methods. The values available for the access attribute are field, property,
or a class name. If you want Hibernate to use reflection and access the Java object’s attribute
directly, use the value "field". To build your own class for accessing the attribute of an object,
use as a value a class that implements net.sf.hibernate.property.PropertyAccessor.
❑<generator> subelement: Defined in the following section, “<generator> Element.”
<generator> Element
When Hibernate needs to add a new row to the database for a Java object that has been instantiated, it
must fill the ID column with a unique value in order to uniquely identify this persisted object. The
<generator> subelement of <id> specifies how the unique identifier should be created. The element
contains a single attribute called class, which specifies the class used to generate the ID. If parameters
are passed to the class, you use the <param name= "">value</param> element. Hibernate includes
a number of built-in generators that we’ll discuss next.
Increment
The increment generator is probably the most familiar creator of IDs. Each time the generator needs to
generate an ID, it performs a select on the current database, determines the current largest ID value, and
increment to the next value. Note that if you’re in a multithreaded environment this generator isn’t safe,
because two or more threads could obtain the same ID value and cause an exception on the database
server.
This generator supports all databases. It has no parameters. The possible column types are short, int, and
long. Here’s some example output:
+--------+------------+----------------------+---------------------+------+
| ID | title | artist | purchasedate | cost |
+--------+------------+----------------------+---------------------+------+
| 1 | Rush | Grace Under Pressure | 2004-04-03 00:00:00 | 9.99 |
| 2 | Nickelback | The Long Road | 2004-04-03 00:00:00 | 11.5 |
+--------+------------+----------------------+---------------------+------+
2 rows in set (0.23 sec)
Identity
If the database has an identity column associated with it, Hibernate can take advantage of the column to
indicate when an object hasn’t been added to the database. Supported databases include DB2, MySQL,
Microsoft SQL Server, Sybase, and HypersonicSQL. Be sure you use this generator with the correct
database. It has no parameters. The possible column types are short, int, and long.
Sequence
If the database has a sequence column associated with it, Hibernate can take advantage of the column to
determine if the object has been added to the database. Supported databases include DB2, PostgreSQL,
Oracle, SAP DB, McKoi, and InterBase. Be sure you use this generator with the correct database. It has
no parameters. The possible column types are short, int, and long.
Hilo
The hilo generator generates unique IDs for a database table. The IDs won’t necessarily be sequential.
This generator must have access to a secondary table that Hibernate uses to determine a seed value for
the generator. The default table is hibernate-unique-key, and the required column is next-value.
You need to insert one row in the table, as you saw in Chapter 3. Here’s a possible table-creation query:
create table hibernate-unique-key next-value int
);
insert into hibernate-unique-key values(100);
The hilo generator must be used with a Hibernate-generated connection. It shouldn’t be used with JTA
connections, according to the Hibernate reference manual.
You can provide three parameters to this generator to change the table name, column name, and maxi-mum
low value. For example:
<generator class="hilo">
<param name="table">hilo</param>
<param name="column">next</param>
<param name="max to">500</param>
</generator>
The possible column types are short, int, and long. Here’s some example output:
mysql> select * from cd;
+--------+------------+----------------------+---------------------+------+
| ID | title | artist | purchasedate | cost |
+--------+------------+----------------------+---------------------+------+
| 131073 | Rush | Grace Under Pressure | 2004-04-03 00:00:00 | 9.99 |
| 163841 | Nickelback | The Long Road | 2004-04-03 00:00:00 | 11.5 |
+--------+------------+----------------------+---------------------+------+
2 rows in set (0.23 sec)
seqhilo
With the seqhilo generator, Hibernate combines the sequence and hilo generators. Supported databases
include DB2, PostgreSQL, Oracle, SAP DB, McKoi, and InterBase. Be sure you use this generator with
the correct database.
You can provide a sequence name with a value of hi_value or low_value depending on the sequence
start. You can also provide a max_lo name with the starting value of the sequence. The possible column
types are short, int, and long.
Uuid.hex
This generator creates a unique strings based on appending the following values: the machine’s IP
address, the startup time of the current JVM, the current time, and the counter value. It supports all
databases and has no parameters. The possible column types are string, varchar, and text. Here’s some
example output:
mysql> select * from cd;
+-------------------+-------+---------------------+---------------------+----+
| ID | title | artist | purchasedate |cost|
+-------------------+-------+---------------------+---------------------+----+
| 40288195fbd50bb...| Rush | Grace Under Pressure| 2004-04-10 00:00:00 |9.99|
+-------------------+-------+---------------------+---------------------+----+
1 row in set (0.00 sec)
Uuid.string
This generator is like Uuid.hex, but the result is a string 16 characters long. It supports all databases except
PostgreSQL, and it has no parameters. Possible column types are string, varchar, and text. In the following
example output, the Marcus Roberts CD is using uuid.string:
mysql> select * from cd;
+--------------+--------------+---------------------+-------------------+-----+
| ID | title | artist | purchasedate |cost |
+--------------+--------------+---------------------+-------------------+-----+
| 40288195f... | Rush |Grace Under Pressure|2004-04-10 00:00:00 |9.99 |
| _¿_§{U?_?... |Marcus Roberts|the truth is spoken |2004-04-10 00:00:00 |13.88|
+--------------+--------------+---------------------+-------------------+-----+
2 rows in set (0.00 sec)
Native
The native generator picks identity, sequence, or hilo, depending on the database.
Assigned
If you need to assign the identifier yourself in your application, then use the assigned generator. You set
the identifier using the set<identifier> method of the Java class. The application assumes the
responsibility of making sure the id value is unique; otherwise, you’ll probably get a database insert
exception.
This generator supports all databases. Some level of application validation may need to occur. It has no
parameters. The column types are application dependent.
Foreign
When a class is part of a one-to-one relationship, it can be helpful to have a common ID between the objects.
By specifying the foreign generator, you make the class use the ID of the other class. This generator sup-ports
all databases and has no parameters.
<composite-id> Element
You can use Hibernate in many different coding situations, including accessing legacy databases. One of
the situations you’ll encounter when using a legacy database is a composite ID. A composite ID is made
up of numerous individual values to form a whole. Hibernate can handle the composite ID using the
<composite-id> element. (Chapter 5 includes a complete example that uses this element.)
The format of the <composite-id> is as follows:
<composite-id
[name=-string"]
[class="string"]
[unsaved-value=" [any] [none]"]
access=" [field] [property] [component class name]"
<key-property/>
<key-many-to-one/>
</composite-id>
There are two versions of <composite-id>. The first doesn’t include the name, class, and unsaved-value,
but uses the <key-property> and <key-many-to-one> elements to map the ID.
For example:
<composite-id>
<key-property name="ss"/>
<key-property name="account"/>
</composite-id>
In another situation, we’ll use a component class to represent the composite ID (as demonstrated in
Chapter 5).
The element’s attributes are as follows:
❑name: Attribute in the component class for the identifier class; the component class for the com-posite
ID.
❑unsaved-value: Default value for the attribute specifying whether the newly instantiated object
should be persisted to the database.
❑access: Possible values: field, property, or a class name. Hibernate accesses an object’s
attribute using traditional JavaBean style setter/getter methods. This form of access is specified
using the property value for the access attribute. If you want Hibernate to use reflection and
access the Java object’s attribute directly, use the value "field". If you want to build your own
class to access the attribute of an object, use as a value a class that implements net.sf.hiber-nate.
property.PropertyAccessor.
<discriminator> Element
If you’re mapping a hierarchy of objects with Hibernate, you have the option of using a mapping of a
table-per-class-hierarchy scheme, as we discussed in Chapter 1. For the single table to work
properly, a column is used to distinguish one class from another in the hierarchy. The <discrimina-tor>
element identifies the column in the table. The format of the element is:
<discriminator
column="column" [optional - defaults to class]
type="type" [optional - defaults to string]
force="true | false" [optional - defaults to false]
The element has three attributes:
❑column: Specifies the name of the column in the table to use as the discriminator column. This
attribute is optional; the default is class.
❑type: Specifies the type of the discriminator column. The default is string if the attribute isn’t
included. The valid types are string, character, integer, byte, short, Boolean, yes no, and true
false. Some of these types will only handle two different classes.
❑force: Determines whether Hibernate uses discriminator values when retrieving all instances of
a root class. This attribute is optional; the default is false.
Notice that the element doesn’t specify the value to place in the column. The value is determined with
the discriminator-value attribute, which we discuss in the sections on the <class> element and
the <subclass> element.
<version> Element
If data in your object needs to be versioned as opposed to having a unique ID, you can use the <ver-sion>
or <timestamp> (discussed next) element to keep the data up to date. There is no generator for
the version or timestamp. The application must handle populating the Java class attribute with the
correct value. You’ll see an example of using a version/timestamp column in Chapter 5.
The format of the element is
<version
column="column" [optional - defaults to name value]
name=”name"
type="type" [optional - defaults to integer]
access="field | property | class" [optional - defaults to property]
unsaved-value="null | negative | undefined"
[optional - defaults to undefined]
/>
The <version> element has five attributes:
❑column: Specifies the name of the column to use for the identifier. This attribute is optional; the
default is the value of the name attribute.
❑name: Specifies the name of the Java class’s version attribute.
❑type: Specifies the type of the version attribute. This attribute is optional; the default is int.
❑access: See the description in our discussion of the <id> element.
❑unsaved-value: Indicates whether the object is newly instantiated. Hibernate uses the value to
determine whether the object needs to be persisted. This is an optional attribute; the default is
undefined.
<timestamp> Element
The <timestamp> element is used in much the same manner as the <version> element. It has five
attributes:
❑column: Specifies the name of the column to use for the identifier. This attribute is optional; the
default is the value of the name attribute.
❑name: Specifies the name of the Java class’s timestamp attribute.
❑type: Specifies the type of the timestamp attribute. This attribute is optional; the default is
int.
❑access: See the description in our discussion of the <id> element.
❑unsaved-value: Indicates whether the object is newly instantiated. Hibernate uses the value to
determine whether the object needs to be persisted. This is an optional attribute; the default is
undefined.
<property> Element
For each of the attributes in your Java class that should be saved to the database when an object is per-sisted,
you need to define a <property> element in the mapping document. The persisted attributes
must be JavaBean compliant. The format of the element is as follows:
<property
name="name"
column="column" [optional - defaults to name value]
type="type" [optional]
update="true | false" [optional - defaults to true]
insert="true | false" [optional - defaults to true]
formula="sql string" [optional]
access="field | property | class" [optional - defaults to property]
/>
The <property> element has seven possible attributes:
❑name: Specifies the name of the property. Note that the first character of the name must
be lowercase.
❑column: Specifies the name of the column in the database table where this attribute should be
saved. This is an optional attribute; Hibernate uses a column name equal to the value of the
name attribute if it’s missing.
❑type: Specifies the name of the Hibernate type for this mapped Java attribute. If the type isn’t
specified, Hibernate attempts to determine the type using reflection. The reflection process isn’t
as easy as you’d expect, but it’s based on a set of rules. The Hibernate types available as well as
the rules are as follows:
❑First attempt: to reflect to a basic type:

Using More Than One Database Server in hibernate

During the development of a complex application, you may need to connect to more than one database
server. This requirement typically arises when you’re developing a replacement application for a legacy
system. The legacy applications has its own database servers, and you may have another one. The new
application code must communicate effectively with all the servers. Of course, you want to keep every-thing
working with Hibernate, so you must have a way to communicate with multiple database servers.
Fortunately, this isn’t a big deal to Hibernate, because it’s all in the configuration file(s). When you
instantiate a Configuration object, the system will by default attempt to find either a hibernate.properties
or a hibernate.cfg.xml file in the application’s root directory. One of these files contains the database con-figuration
information needed to contact a database server. To communicate with a second database
server, you need another configuration file.
For example, let’s say we have a MySQL database and a Microsoft SQL Server database that will be used
in an application. We’ll let the hibernate.cfg.xml file contain the connection and mapping information for
the MySQL database. For the Microsoft SQL Server database, we’ll build a configuration file called
sqlserver.cfg.xml, which looks like this:
<?xml version="I.0" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd>
<hibernate-configuration>
<session-factory>
<property name="connection.driver class">
com.microsoft.jdbc.Driver</property> <property name="connection.url">
jdbc.Microsoft://localhost/products</property> <property
name="username">sa</property>
<property name="password">sa</property>
</session-factory>
</hibernate-configuration>
We now have two different configuration files for our databases. Next we create an application that uses
the files. Here’s an example piece of code:
Configuration configuration = new ConfigurationO.addClass(CD.class);
SessionFactory mysqlSession = configuration.buildSessionFactoryQ;
configuration = new Configuration().
configure("sglserver.cfg.xml").addClass(CD.class);
SessionFactory sqlserverSession = configuration.buildSessionFactoryO;


This code handles two different database servers. Remember, the key to using Hibernate is the
SessionFactory built from a Configuration object. The first part of the code creates a
Configuration object and a SessionFactory object using the technique from Chapter 3. This code
uses the default hibernate.cfg.xml file for its connection and mapping information.
The trick to using multiple databases comes into play in the second part of the code. Here we build a
new Configuration object, but we use a method called configure() to bring in the SQL Server con-figuration
file. The configure() method accepts an XML document that adheres to the hibernate-con-figuration-
2.0.dtd file. Our configuration file is designed to work with hibernate-configuration-2.0.dtd;
as such, the Configuration object gladly accepts it as a valid configuration file. Subsequently, the
object ignores the default configuration file.

JDBC Database Connection in hibernate

As an experiment in how Hibernate uses a database connection, remove or rename the file hibernate
.properties, or remove the database elements in hibernate.cfg.xml (if you’re using it), in either the stand-alone
or servlet application written in the previous chapter. When you’ve changed the file, execute the
application and attempt an action that accesses the database, such as showing all the CDs. Since our
error handling displays the stack trace, you should get a fairly large trace dump on the console window
where you launched the application. If you’re using the servlet example, you might need to open a log
file to see the errors.
At the top of the stack trace, you should see a message like “user needs to supply connection”. This error
tells you that Hibernate was unable to obtain a connection to any database for more than just a wrong
password. But, in fact, no hibernate.properties file or database elements are available to the application;
as such, the application doesn’t know how to connect to a database. This is obviously bad, because
Hibernate accomplishes most of its work through a database.
The point is, the developers of Hibernate developed the system in a manner that lets you handle a vari-ety
of design situations. In this case, Hibernate can either create its own connection to the underlying
database or use a connection that’s already in place. The examples in Chapter 3 show you how to use
Hibernate connections. If you’re developing an application from scratch, you’ll probably let Hibernate
handle the connection; there aren’t any glaring issues with this type of situation, and there are no perfor-mance
problems. So, why does Hibernate allow user-based connections? Primarily to handle legacy
issues.
Given the constant evolution of software systems, you won’t always be able to rewrite your code. In
some cases, you must refactor live systems. The application has already been written, and database con-nections
are established and available, so why not use them? You need to consider a couple of issues.
The first is connection pooling, which we discuss in detail later in this chapter. If you’re using a previ-ously
established connection, you’ll bypass any connection pooling defined in Hibernate. Second is the
issue of transactions. When you’re using a user-based connection, you can use Hibernate’s transaction
system (discussed in Chapter 10), or the application can handle transactions through the underlying
database using JDBC transactions or through JTA.
Here’s an example of the code for using a previously established connection:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.
getConnection("jdbc:mysql://localhost/accounts");
SessionFactory sessionFactory = Configuration.buildSessionFactory();
Session session = sessionFactory.openSession(connection);
} catch (Exception e) {}