Hibernate in XPages

Post on 06-Dec-2014

477 views 6 download

Tags:

description

 

transcript

MWLUG 2014

AD106 Don't fall asleep using Relational Databases: Using Hibernate with XPages

Toby Samples, PSC Group, Consultant

About Toby

Over 10 years as a Web Developer using various technologiesASP.net J2EEPHPXPages

Consultant at PSC Group LLC• XPages® Developer • Contact Information• Blog: http://www.tobysamples.com• Email: tsamples@psclistens.com• Twitter: @tsamples• Skype: toby.samples23

www.psclistens.com @pscgroup

• Agenda– Pre-requisites– Intro to RDBMS– Intro to Hibernate– Download and Install + adding to DDE– Create Hibernate Configuration– Run Code Generation– Copy Java files to DDE– Util code for Hibernate– CRUD Code– XPages Code– Questions

• Pre-requisite knowledge

– Understand How to write an Xpage application– How to add a Jar/Java Library to an Xpages application

• Build Path Configuration– Some knowledge of How to use Java in XPages– Where to find errors from Java code in XPages

• Oh no, I have to use Relational Databases

• Using the Domino API vs RDBMS

– We’ve been lucky (More code to doing Relational Database persistence)

– Pros to using RDBMS• Tools – Lots of them• Vendors – Varied with many strengths and niches• Scales (Size Limit) • Transactional• Truly relational, can have constraints and triggers

– Hibernate has a strong connection to the Domino API

• RDBMS - Another tool in the toolbox

– Not your enemy

– Relational Databases are everywhere

– You probably already have some in your environment

– Even if you use an RDBMS as your data store you can still leverage all the other pieces of Domino in your XPages app• Security• NAB• XPages Knowledge (XSP, Dojo, Java, ssjs) already baked in.

• History of Connecting to Relational Databases in Java– JDBC– J2EE JRE 1.2 released in 1999

• DAO Design Pattern– Became a defacto standard and is still in use today.– Requires lot of code to be hand written – Builds on JDBC API to create an easier way to persist data.

• JPA 1.0– Released in JRE 1.5 2006 – JSR 220 Expert Group– Eclipselink became the reference implementation

• Why use an Object Relational mapping

– Relational Database are table-driven, with rows and columns, they are designed for fast queries

– In Java we are used to working with Objects that have properties with getters and setters.

– If you don’t use an ORM you have to do this mapping yourself from the standard JDBC Connection after you run a SQL Query

– With an ORM the developer gets to focus on Java

– ORM Solutions are mature

• Hibernate– Created in 2001 as a way to put more of an abstraction layer

between applications and Databases.– Jboss hired the developers and started investing in Hibernate in

2005– OpenSource with an LGPL license

– Originally used XML Mapping files– After JDK 5 was released implemented Annotations

• What is Hibernate– Object/Relational Mapping

• JPA Provider• Entities• JPQL

Hibernate ToolsMapping EditorReverse Engineering

Other Hibernate ModulesHibernate SearchHibernate ValidatorHibernate OGM (NoSQL)

• Why use Hibernate– Performance

• High Performance Object Caching• Configurable Strategies

– Awesome Query abilities• Criteria API• Query By Example• HQL • Native SQL

– Proven used all over the world in J2EE applications

• Why use Hibernate to connect to RDBMS?

– There are other options• JDBC Connections• Extension Library Tooling

Because you’re lazy OK, you’re efficient!Automatic CachingConnection Pooling (C3P0 or DBCP)Hibernate’s tooling and code generation makes life so much easier when dealing with relational databases. Hibernate abstracts away database independence, (same code, no matter the vendor, just change the dialect)NO SQL NEEDED, no really.

• Hibernate Architecture

• Hibernate Architecture– The architecture abstracts

away the underlying JDBC, JNDI, and JTA API’s, and lets the Hibernate engine take care of all of the plumbing

• Domain Classes

– Domain Classes are Java Classes that implement the objects or “entities” that make up your business process and application• Invoice• PurchaseOrder• ShippingItem

– These Objects are usually very simple and follow the rules to be POJOs

• Writing Domain Classes– Must have a no-argument constructor

– Has to have an identifier property• It maps the primary key of the database table• Shows the mapping to the database table column• Has to show the type whether it’s a string, or integer, or Boolean, etc• Can have other options such as how the ID is generated

– Declares getters and setters for fields that are to be persisted in the database

• Saving Objects– An Object is considered transient until it has been saved by the

Hibernate Session, once it has been saved it is considered persistent and is tied to that instance of Hibernate Session

– Once saved Objects get updated with their Object Identifier

• How to Save Objects– In the Session Interface or class

– public Serializable save(Object object) • Saves the transient object• Assigns the Object Identifier to the object• Returns the Object Identifier

• Example of saving an Object

Student student = new Student();student.setFirstName(“Joe”);student.setLastName(“Smith”);student.setEmail(“joe.smith@mwlug.com”);Object id = session.save(student); Id now represents the object identifier for the persisted object

• Getting Objects

– You can also use hibernate to pull a record out of the database into a persisted object.

– Using get() vs load()

• Get will return null if the unique id specified doesn’t exist• Load will throw an exception if the unique id doesn’t exist

• Get and Load examples

Public Object get(Class clazz, Serializable identifier)

Put in the type of object you want to return and the id and it will return that object from the database into your newly created persisted object.

• Getting an object example

Student student = (Student)session.get(Student.class, id);If (student == null) {

System.out.println(“Student does not exist with id “ + id);

}

• Refreshing Objects

– Refreshing persistent objects allows you to know that the data that is in the object is in sync with what is in the database.

– If your database is used by more than just your Hibernate application it’s a good idea to use this functionality as you don’t know exactly when the database row may have been updated

– However if that’s not the case this has a large performance cost because it makes another call to the SQL database

• Updating Objects– Hibernate automatically manages changes to the persistent objects

• If a property changes on a persistent object, then it will be updated in the database once the object is commited

– You can force Hibernate to commit all objects by calling the flush() method on the session object

– You can also use the isDirty() method to determine the status of all of the persisted objects

• Deleting Objects– Used to delete objects from the Database table

• Session.delete(Object) will delete the database record• Transactions are available to ensure that if there is an issue it will be

rolled back.

• Querying Data– Hibernate returns data back in standard Java Data Collections such

as Lists and Sets– There are several ways to query data

• Criteria API• Query By Example • Hibernate Query Language• Native SQL

• Querying Data– All of these querying methods return back Persisted objects so it is

easy to get a handle on a returned object change it and update the data in the database.

– Example Query by Example

public void testEquals() throws Exception { Session session = (Session) entityManager.getDelegate(); Address address = new Address(); address.setCountryISO2Code("US"); address.setCity("CHICAGO"); Example addressExample = Example.create(address); Criteria criteria = session.createCriteria(Address.class).add(addressExample); listAddresses(criteria.list());}

Hibernate Framework Classes

• Org.Hibernate.Session– Single Threaded– Short lived– Represents the conversation between the application and the

database– Called a “persistence Context”

• A Persistence Context is a container of objects that are being persisted– Handles CRUD for the database

• Create• Read• Update• Delete

– Also holds a factory for creating Transactions

• Org.hibernate.Transaction– Single threaded– Short lived– Specifies a very specific small unit of work on the database– Keeps us from having to deal with the JTA framework– Mandatory

• Any and all database operations must be done within the context of a transaction

– Commit and Rollback

Hibernate Configuration

• Hibernate Configuration– Hibernate Configuration File

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory name="hibernateSessionFactory"> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.search.autoregister_listeners">false</property> <mapping class="com.mwlug.demo.hibernate.Notes" /> </session-factory></hibernate-configuration>

• Object to Table Mapping– Mapping through Mapping XML Configuration Files

• Add configuration of file in main hibernate configuration file– <mapping resource=“/Employee.mapping.xml” />

• Create Mapping File<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package=“com.mwlug.demo.hibernate">     <class name="Employee" table="EMPLOYEE">        <id name="employeeId" column="EMPLOYEE_ID">            <generator class="native" />        </id>        <one-to-one name="employeeDetail" class=“com.mwlug.demo.hibernate.EmployeeDetail"            cascade="save-update"></one-to-one>                 <property name="firstname" />        <property name="lastname" column="lastname" />        <property name="birthDate" type="date" column="birth_date" />        <property name="cellphone" column="cell_phone" />     </class></hibernate-mapping>

• Object to Table Mapping– Using Annotations to Map database tables to Classes– Add mapping to congiguration file

• <mapping class="com.mwlug.demo.hibernate.Equipment" />

– Annotations within Code

• Object to Table Mapping

Download

Java Library

Hibernate.orgHibernate ORM

ToolsEclipse.org/downloads

Eclipse IDE for Java EE Developers

Hibernate.orgHibernate Tools (Update Site for eclipse)

• Install– Installing Eclipse

• After downloading unzip into folder and run eclipse.exe – No Install

– Installing Hibernate Tools• Load up Eclipse

– Help Menu /Install New Software» Create new Update site: http

://download.jboss.org/jbosstools/updates/stable/kepler/» Search for Hibernate Tools» Install and restart Eclipse

• Install

– Adding Jar files to Domino Server• Unzip and Extract files from hibernate-release-4.3.6.Final.zip to its own

folder• Take all of the jar files out of their respective folders and put into either

an OSGI Plugin or <DominoProgramFolder>/jvm/lib/ext– This is both for ease of installation and for security

• Restart Domino Server

• Demo

• Closing thoughts– RDBMS can be pretty quick to develop– Doesn’t have to be the entire app– Use tools that make your life easier as a developer

• The Best Code is No Code At All– Let tried and true tools write code– Use libraries that have been time tested– Use datastores that work and have large user bases

• Yay I get to use Hibernate

• References– Hibernate.org

• http://www.hibernate.org

– JPA Documentation• http://docs.oracle.com/javaee/6/tutorial/doc/bnbpz.html

Questions