hibernate in xpages

47
MWLUG 2014 AD106 Don't fall asleep using Relational Databases: Using Hibernate with XPages Toby Samples, PSC Group, Consultant

Upload: toby-samples

Post on 06-Dec-2014

484 views

Category:

Technology


6 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Hibernate in XPages

MWLUG 2014

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

Toby Samples, PSC Group, Consultant

Page 2: Hibernate in XPages

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: [email protected]• Twitter: @tsamples• Skype: toby.samples23

www.psclistens.com @pscgroup

Page 3: Hibernate in XPages
Page 4: Hibernate in XPages

• 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

Page 5: Hibernate in XPages

• 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

Page 6: Hibernate in XPages

• Oh no, I have to use Relational Databases

Page 7: Hibernate in XPages

• 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

Page 8: Hibernate in XPages

• 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.

Page 9: Hibernate in XPages

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

Page 10: Hibernate in XPages

• 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.

Page 11: Hibernate in XPages

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

Page 12: Hibernate in XPages

• 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

Page 13: Hibernate in XPages

• 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

Page 14: Hibernate in XPages

• What is Hibernate– Object/Relational Mapping

• JPA Provider• Entities• JPQL

Hibernate ToolsMapping EditorReverse Engineering

Other Hibernate ModulesHibernate SearchHibernate ValidatorHibernate OGM (NoSQL)

Page 15: Hibernate in XPages

• 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

Page 16: Hibernate in XPages

• 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.

Page 17: Hibernate in XPages

• Hibernate Architecture

Page 18: Hibernate in XPages

• 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

Page 19: Hibernate in XPages

• 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

Page 20: Hibernate in XPages

• 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

Page 21: Hibernate in XPages

• 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

Page 22: Hibernate in XPages

• 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

Page 23: Hibernate in XPages

• Example of saving an Object

Student student = new Student();student.setFirstName(“Joe”);student.setLastName(“Smith”);student.setEmail(“[email protected]”);Object id = session.save(student); Id now represents the object identifier for the persisted object

Page 24: Hibernate in XPages

• 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

Page 25: Hibernate in XPages

• 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.

Page 26: Hibernate in XPages

• 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);

}

Page 27: Hibernate in XPages

• 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

Page 28: Hibernate in XPages

• 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

Page 29: Hibernate in XPages

• 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.

Page 30: Hibernate in XPages

• 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

Page 31: Hibernate in XPages

• 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());}

Page 32: Hibernate in XPages

Hibernate Framework Classes

Page 33: Hibernate in XPages

• 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

Page 34: Hibernate in XPages

• 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

Page 35: Hibernate in XPages

Hibernate Configuration

Page 36: Hibernate in XPages

• 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>

Page 37: Hibernate in XPages

• 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>

Page 38: Hibernate in XPages

• 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

Page 39: Hibernate in XPages

• Object to Table Mapping

Page 40: Hibernate in XPages

Download

Java Library

Hibernate.orgHibernate ORM

ToolsEclipse.org/downloads

Eclipse IDE for Java EE Developers

Hibernate.orgHibernate Tools (Update Site for eclipse)

Page 41: Hibernate in XPages

• 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

Page 42: Hibernate in XPages

• 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

Page 43: Hibernate in XPages

• Demo

Page 44: Hibernate in XPages

• 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

Page 45: Hibernate in XPages

• Yay I get to use Hibernate

Page 46: Hibernate in XPages

• References– Hibernate.org

• http://www.hibernate.org

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

Page 47: Hibernate in XPages

Questions