Using Hibernate to build Applications for Informix

treeexcellentΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 7 μήνες)

59 εμφανίσεις

Using Hibernate to build
Applications for Informix
Nita Dembla
IBM

2
Agenda
Introduction
- Introduction to ORM
- Overview of Hibernate
- Why Hibernate?
- Example of JAVA class
- Example of Mapped Database Table
Setup and Configuration
- Components of Hibernate Application
- System Software Requirements
- Installing Hibernate
- Configuring CLASSPATH
- Hibernate Configuration File
- Configuring Hibernate for Informix
- XML Mapping File

3
Agenda
Using Hibernate with IBM Informix Database
- HibernateUtil class
- Building Hibernate Application
- Using Hibernate in Java Application
Annotations
- Using Annotations in Java Application
Demo
Questions

4
Introduction to ORM
ORM stands for Object Relational Mapping.
Maps Java Objects to Relational Tables.
Pesists Objects in a Relational Database.
Supports CRUD (Create, Read, Update and Delete) operations.
Provides RDBMS Vendor independence.

5
Overview of Hibernate
Open source Java ORM and persistence framework.
Uses XML based config files for mapping Java Objects to relational database
tables.
Java APIs to store and retrieve the state of Java objects into a database.
Generates the JDBC Code based on the underlying vendor database
Provides Connection and Transaction management
services.


6
Why Hibernate?
Allows developers to focus on the business logic of the application.
Developers do not have to deal with SQL and JDBC calls.
Produces more robust and portable code, which means faster development
time.
Hibernate APIs are very simple to learn and use
Very well matured and adopted by a large developer community.
Provides powerful object query language known as Hibernate Query Language
(HQL).

7
Example JAVA Class
public class State {
private Long id;
private String code;
private String sname;
public State() {}
public State(String text, String text2) {this.code = text; this.sname = text2;}
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getcode() {return code;}
public void setcode(String text) {this.code = text;}
public String getsname() {return sname;}
public void setsname(String text) {this.sname = text;}
}

8
Example - Database Table
id
code
sname
1
AZ
Arizona
2
GA
Georgia

Create table state(
id serial,
code char(2),
Sname varchar(255)
)

9
Components of a Hibernate
Application

10
System Software Requirements
IBM Informix Database Server
IBM Informix Java Database Connectivity (JDBC) Driver or IBM Dataserver
Driver for JDBC.
Hibernate package.
JDK Java 1.5 or higher.
Eclipse or comparable IDE for developing and running Java applications.

11
Installing Hibernate
Hibernate is an open source project that you can download from:
http://sourceforge.net/projects/hibernate/files
The latest version of Hibernate API is V4.1.11.
The compressed package name is hibernate-distribution-4.1.11-Final-dist.zip.
Package contains:
Java libraries
Documentation
Source code project files for libraries
SQL Dialects for supported Database vendors

12
Informix Dialect in Hibernate
A Hibernate dialect is a Java class containing specific details regarding the SQL
syntax needed to communicate with a particular database.
Hibernate 3.x.x and prior versions come with an older Informix Dialect. This
Dialect does not have support for BLOB/CLOB and Binary types.
Hibernate V4.x.xx comes with latest Informix Dialect available. If you
plan to use an older Hibernate version, you can download the latest
Informix Dialect from
https://github.com/lfeagan/hibernate-
orm/blob/2e42501b203190558c68aade4cec2f5fac8334de/hibernate-
core/src/main/java/org/hibernate/dialect/InformixDialect.java

13
Configuring CLASSPATH
Environment variable that tells the Java compiler and the Java Virtual Machine
(JVM) where to look for Java class files and Java libraries.
To use Hibernate with a Java program and Informix server, include in
CLASSPATH -
All the libraries in the
lib/required
directory of Hibernate package
IBM Informix JDBC

driver jar file
If using Hibernate 3.x or older, an implementation of the SLFJ logger (Install
from
http://www.slf4j.org/download.html)

14
Configuring CLASSPATH
Example using Hibernate 4.1.11:
export CLASSPATH=$CLASSPATH:.:/work/lib/commons-annotations-4.0.1.Final.jar:
/work/lib/dom4j-1.6.1.jar:/work/lib/hibernate-jpa-2.0-api-1.0.1.Final.jar:
/work/lib/hibernate-core-4.1.11.Final.jar:/work/lib/javassist-3.15.0-GA.jar:
/work/lib/jboss-transaction-api_1.1_spec-1.0.0.Final.jar:
/work/lib/slf4j-api-1.6.1.jar:/work/lib/antlr-2.7.7.jar:/work/lib/jboss-logging-3.1.0.GA.jar:
/work/lib/ifxjdbc.jar

15
Hibernate Configuration File
Two alternative methods for specifing configuration parameters:
hibernate.properties:
A standard java properties text file
hibernate.cfg.xml:
An XML formatted file
XML configuration file overrides the settings in the properties text file.
Contains the information Hibernate needs to connect to the database server.
Configuration file (
hibernate.properties
or
hibernate.cfg.xml
) should be located in the root
directory of the CLASSPATH or the “src” directory of your project.
Can optionally include the XML mapping files for object to tables mapping.

16
Configuring Hibernate for Informix
When using the IBM Informix JDBC Driver with Hibernate, the dialect must be
set
to
orb.hibernate.dialect.Inform ixDialect
.
db.dialect = org.hibernate.dialect.InformixDialect
jdbc.driver = com.informix.jdbc.IfxDriver
Other key values to configure for IBM Informix Database Server are:
jdbc.url - host name, port number, database name, INFORMIXSERVER
property, jdbc.user, jdbc.pass

17
Sample XML Configuration File
?
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="hibernate.connection.driver_class">
com.informix.jdbc.IfxDriver
</property>
<property
name="hibernate.dialect">
org.hibernate.dialect.InformixDialect
</property>
<property name="hibernate.connection.username">
informix
</property>
<property name="hibernate.connection.password">
informix
</property>
<property name="hibernate.connection.url">
jdbc:informix-
sqli
://ADMINIB-
PGNIBNJ:turbo/stores_demo:INFORMIXSERVER=ol_1210;
</property>
<mapping class="State" resource="State.hbm.xml"/>
</session-factory>
</hibernate-configuration>

18
XML Mapping File
Common naming convention is Objectname_hbm.xml (eg: State_hbm.xml)
Used to specify the relations between a Java object and an SQL database
object.
Mapping definitions allows Hibernate to

Persist the Java objects into the relational database.

Creating the database schema and relationship between the objects.
Mapping can include other column attritubes such as NOT NULL.
Include the filename in mapping section in hibernate configuration file
(hibernate.cfg.xml)
XML mapping files are not required when using Java annotations.

19
Sample XML Mapping File
<?
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="State" table="STATE">
<id name="id">
<column name="ID"/>
<generator class="increment"/>
</id>
<property name="code">
<column name="CODE"/>
</property>
<property name="
sname
">
<column name="SNAME"/>
</property>
</class>
</hibernate-mapping>

20
Generating Hibernate Configuration
Files
You can optionally generate the Hibernate configuration and mapping files.
Download the Hibernate Plugin for Eclipse that comes with an XML editor for
configuration files.
Simply set the values in the XML editor and the files will be automatically
generated.

21
HibernateUtil class
The HibernateUtil class is a “helper class” used to interact with the Hibernate
service.
Performs the operations related to the Hibernate SessionFactory class.

SessionFactory class provides an easy way for the application to access the
Hibernate session.
SessionFactory class allows connection to the database server using
configuration specified in hibernate.cfg.xml.
The Java file containing the HibernateUtil helper class is HibernateUtil.java.

22
Example HibernateUtil class
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
// Creates the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory()
;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}

23
Building Hibernate Application
Developing a Hibernate application includes the following steps:
- Create the Java objects.
- Create the XML Mapping files for the Java objects.
- Create the configuration file with Informix Server and Dialect information.

Create the HibernateUtil helper class that provides access to the Hibernate
session.

Create the application that would use the Java persistence objects.

Ensure IBM Informix Server is running.

Configure CLASSPATH.

Compile and run the Java hibernate application.

24
Using Hibernate in Java Application
Create a Hibernate Session instance using the
H ibernateU til
helper class.
Session Session =
HibernateUtil.
getSessionFactory
().openSession();
Create Java objects to persist.
State myState =
new
State();
Save the state of the object in the database table
Session.save(myState); Trasaction.commit();
Loading an object from database table
Session.load(myState, 1); OR
Session.get(myState, 1); OR
List states = newSession.createQuery("from State").list();

25
Using Hibernate in Java Application
Updating an
object in the database table
Session.get(myState, 1);
//update myState object
Session.save(myState);
Trasaction.commit();
Delete an object from database table
Session.delete(myState, 1);
Trasaction.commit();
Cleanup Session
Session.close();
Hibernate.Shutdown();
Transaction support
Transaction.commit();
Transaction.rollback();

26
Annotations
Links the Java objects with the database objects.
Provides an alternative to using XML mapping file.
Mapping is embedded in the Java code.
Annotations such as
@Entity
,
@ Table
or
@Colum n
define the
mapping information needed to
persist
the Java objects into the database
Needs JDK 1.6+

27
Example using Annotations
@Entity
@Table(name="States")
public class State {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY )
@Column(name="id")
public Long getId() {
..
@Column(name="code", length=2, nullable=false)
public String getcode() {
..

28
Using Annotations
HibernateUtil helper class (HibernateUtil.java) should use the
AnnotationConfiguration() interface
AnnotationConfiguration() interface retrieves the Hibernate properties and the
metadata definition from the object class.
Example:
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new AnnotationConfiguration()
.configure()
.
addAnnotatedClass(State.class
).buildSessionFactory();
..
}

29
DEMO
DEMO is done using
IBM Informix Database 12.10FC1
Eclipse Juno
Hibernate 4.1.11
JRE 1.6

30
Resources
Hibernate information
http://docs.jboss.org/hibernate/stable/core/reference/en/html/
IBM Informix Developer's Handbook
http://www.redbooks.ibm.com/redpieces/abstracts/sg247884.html?Open&pdfbookmark
Youtube for free Hibernate Tutorials
http://www.youtube.com/watch?v=GINvxAaXDbY

IBM
’s statements regarding its plans, directions, and intent are subject to change or
withdrawal without notice at IBM’s sole discretion.

Information regarding potential future products is intended to outline our general
product direction and it should not be relied on in making a purchasing decision.

The information mentioned regarding potential future products is not a commitment,
promise, or legal obligation to deliver any material, code or functionality. Information
about potential future products may not be incorporated into any contract. The
development, release, and timing of any future features or functionality described for
our products remains at our sole discretion.
Please Note:

Performance is based on measurements and projections using standard IBM
benchmarks in a controlled environment. The actual throughput or performance that
any user will experience will vary depending upon many factors, including
considerations such as the amount of multiprogramming in the user's job stream, the
I/O configuration, the storage configuration, and the workload processed. Therefore,
no assurance can be given that an individual user will achieve results similar to those
stated here.
04/19/13
32

Availability
. References in this presentation to IBM products, programs, or services
do not imply that they will be available in all countries in which IBM operates.


The workshops, sessions and materials have been prepared by IBM or the session
speakers and reflect their own views. They are provided for informational purposes
only, and are neither intended to, nor shall have the effect of being, legal or other
guidance or advice to any participant. While efforts were made to verify the
completeness and accuracy of the information contained in this presentation, it is
provided AS-IS without warranty of any kind, express or implied. IBM shall not be
responsible for any damages arising out of the use of, or otherwise related to, this
presentation or any other materials. Nothing contained in this presentation is intended
to, nor shall have the effect of, creating any warranties or representations from IBM or
its suppliers or licensors, or altering the terms and conditions of the applicable license
agreement governing the use of IBM software.


Acknowledgements and
Disclaimers
:


Acknowledgements & Disclaimers
:

© Copyright IBM Corporation 2013. All rights reserved.

U.S. Government Users Restricted Rights - Use, duplication or disclosure
restricted by GSA ADP Schedule Contract with IBM Corp.

Please update paragraph below for the particular product or family brand trademarks
you mention such as WebSphere, DB2, Maximo, Clearcase, Lotus, etc
IBM, the IBM logo, ibm.com,
[IBM Brand, if trademarked],
and
[IBM Product, if trademarked]

are trademarks or registered trademarks of International Business Machines Corporation in
the United States, other countries, or both. If these and other IBM trademarked terms are
marked on their first occurrence in this information with a trademark symbol (® or ™), these
symbols indicate U.S. registered or common law trademarks owned by IBM at the time this
information was published. Such trademarks may also be registered or common law
trademarks in other countries. A current list of IBM trademarks is available on the Web at
“Copyright and trademark information” at
www.ibm.com/legal/copytrade.shtml
If you have mentioned trademarks that are not from IBM, please update and add the
following lines:
[Insert any special 3rd party trademark names/attributions here]
Other company, product, or service names may be trademarks or service marks of others.
Do you have a great presentation topic that
you’d like to share?

We’re looking for dynamic, innovative and thought-provoking sessions

Whether your proposal aims at sharpening skills, sharing best
practices, or presenting new ideas and groundbreaking concepts, all
proposals are welcome

Visit the
conference website
to learn more
 
The Call for Speakers closes April 30! Hurry to submit your session!
Sign Up! Informix Usability Sandbox!
Help shape the future of Informix.
Influence Informix usability and functionality.
Share your experiences and feedback.
Usability Sandbox
sessions in
Santa Fe 3
April 22-24th, between 9am and 5pm
Sign-up at the IBM Information Table or find Justin McDavid.
*The first 20 participants will get a free IBM t-shirt!

36
Questions?
Using Hibernate to build Applications for Informix
Nita Dembla
IBM
nita@us.ibm.com