P. 1
Hibernate

Hibernate

|Views: 5|Likes:
Published by vbreddy07

More info:

Published by: vbreddy07 on Aug 28, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

12/13/2015

pdf

text

original

[

Hibernate in 60 Minutes

]

Eric M. Burke www.ericburke.com

April 14, 2005

Hibernate in 60 Minutes

1

[
  

My JDBC Experience

]

Frustration drove me to investigate Hibernate  Custom JDBC frameworks and idioms

Usually a class called JdbcUtil with static methods Database metadata is too cool to resist

Custom code generators

Custom strategy for optimistic locking  Database-specific ID generation
April 14, 2005 Hibernate in 60 Minutes 2

2005 Hibernate in 60 Minutes .[  Typical JDBC Problems  ] Massive duplication  Tied to specific database  Error-prone try/catch/finally Relationships are really hard ○ ○ N+1 selects problem parent/child updates  delete all then add  Screen-specific DAOs for optimization 3 April 14.

additional build complexity? Does it simplify my life? April 14. JAR files.[   Hibernate Questions ] How hard is it to learn and use?  How invasive is it to my code?  What are the configuration headaches? ○ Yet another framework with XML files. 2005 Hibernate in 60 Minutes 4 .

MySQL. etc. SAP DB. Progress.[   What is Hibernate? Java Object/Relational Mapping ○ ○ ] Open source – LGPL http://www. Ingres. Mckoi. Or you can extend one of the Dialect classes Hibernate in 60 Minutes 5 ○ April 14. Interbase.org/ (JBoss Group) Lets you avoid SQL  Works with (almost) all relational DBs ○ DB2. HSQLDB.. Sybase. FrontBase. SQL Server. 2005 .. Pointbase. Informix. Oracle. PostgreSQL.hibernate.

[    What is Hibernate? (Cont'd) Has a huge feature list ○ ] Go to their web site – we don't have time XML defines the mappings Very few bean requirements As opposed to bytecode manipulation New database? No problem! Change a few props Hibernate in 60 Minutes 6 Maps JavaBeans (POJOs) to tables ○ ○ SQL is generated at app startup time ○ ○ April 14. 2005 .

} catch (HibernateException e) { JavaBeans throw new DaoException(e).eq("screenName". screenName)). } Property Name }  Code-based query API public User getByScreenName(String screenName) { return getUnique(Expression. } April 14.uniqueResult().[  Avoiding SQL Hibernate Query Language approach ] public User getByScreenName(String screenName) { try { return (User) getSession().createQuery( "from User u where u. screenName) .screenName=:screenName") . 2005 Hibernate in 60 Minutes 7 .setString("screenName".

// assume we know the root category id is 1 Category rootCategory = (Category) session.[ Sample Application Code ] Session session = getSessionFactory(). } session.println(). April 14.getBody()).out. // generics+XDoclet==bad System.close().openSession().println(“Body: “ + msg.out.out. System. System. 2005 Hibernate in 60 Minutes 8 . // we can immediately traverse the collection of messages // without any additional Hibernate code for (Object msgObj : rootCategory. new Long(1)).println(“Subject: “ + msg.getSubject()).class.load( Category.getMessages()) { Message msg = (Message) msgObj.

[ Sample Code with Transaction ] Session sess = . 2005 Hibernate in 60 Minutes 9 . April 14.isNull("parentCategory")).class). tx. Transaction tx = sess. sess. Category rootCategory = (Category) criteria..commit().uniqueResult().createCriteria(Category. criteria.close(). // find the root category using Criteria Criteria criteria = sess. // change something rootCategory.setDescription(“The Root Category”).add(Expression..beginTransaction().

2005 .[   Development Options Start with the database ○ ○ ] Use middlegen to generate mapping files Use hbm2java to generate JavaBeans Use XDoclet to generate mapping files Use hbm2ddl to generate the database Hand-code the mapping files Use both hbm2java and hbm2ddl Hibernate in 60 Minutes 10 Start with JavaBeans C ○ ○  Start with the XML mapping files ○ ○ April 14.

cfg.[   Hibernate Tutorial ] Design the database  Code some persistent classes  Write an Ant buildfile ○ Generate the mapping files and hibernate.xml Choose a strategy for sessions and transactions (Spring framework)  Write and test the DAOs  Add business logic and helper methods April 14. 2005 Hibernate in 60 Minutes 11 .

FK1 PK.FK2 categoryId resourceId FK1 many-to-many April 14. 2005 Hibernate in 60 Minutes 12 .[  Database Design Design your database first Categories ] Resources PK id name url description createdOn PK id name description parentCategoryId Surrogate Keys Work Best many-to-one CategoriesResources PK.

[   Persistent Objects POJOs .Plain Old Java Objects ○ ] No base class or interface requirement Must have public no-arg constructor  Should have getter/setters ○ ○ Or Hibernate can access fields directly Hibernate uses JavaBeans property names  For mappings as well as in queries Serializable is recommended  XDoclet tags are useful but not required  April 14. 2005 Hibernate in 60 Minutes 13 .

2005 Hibernate in 60 Minutes 14 .id = id. /** * @hibernate. private Long id. } ] assigns the id } April 14.id * column="id" * unsaved-value="null" * generator-class="native" * access="field" */ public Long getId() { Hibernate return id. } private void setId(Long id) { this.[ My Base Class public class PersistentClass implements Serializable { private static final long serialVersionUID = 1.

[ Category Class private Set childCategories = new HashSet(). private Category parentCategory. } public void setChildCategories(Set childCategories) { this. not Hibernate's public class Category extends NameDescription { private static final long serialVersionUID = 1. } ] My base class. 2005 Hibernate in 60 Minutes 15 . description). } public Set getChildCategories() { return childCategories. public Category() { } public Category(String name.childCategories = childCategories. private Set resources = new HashSet(). April 14. String description) { super(name.

} public void setResources(Set resources) { this. 2005 Hibernate in 60 Minutes 16 . } public Set getResources() { return resources. } public void setParentCategory(Category parentCategory) { this. } ] } April 14.[ Category (Cont'd) public Category getParentCategory() { return parentCategory.parentCategory = parentCategory.resources = resources.

Category" table="Categories"> <id name="id" column="id" type="java.Category" cascade="none" column="parentCategoryId" not-null="false"/> April 14. 1 per persistent bean <hibernate-mapping> <class name="com.ericburke. 2005 Hibernate in 60 Minutes 17 .linkblog.linkblog.Category"/> </set> <many-to-one name="parentCategory" class="com.linkblog.[  Mapping Files Or Java 5 Annotations ] Generated by XDoclet.Long" unsaved-value="null"> <generator class="native"/> </id> <set name="childCategories" lazy="true" inverse="true" cascade="save-update"> <key column="parentCategoryId"/> <one-to-many class="com.model.model.ericburke.lang.ericburke.model.

linkblog.Resource"/> </set> <property name="name" type="java.model.String" column="description" length="2000"/> </class> </hibernate-mapping> April 14.lang.lang.String" column="name" length="255"/> <property name="description" type="java. 2005 Hibernate in 60 Minutes 18 .[ Mapping Files (Cont'd) ] <set name="resources" table="CategoriesResources" lazy="true" cascade="save-update"> <key column="categoryId"/> <many-to-many column=”resourceId” class="com.ericburke.

} // no tags on the setters public void setChildCategories(Set childCategories) { } April 14.model.Category" */ public Set getChildCategories() { return childCategories. 2005 Hibernate in 60 Minutes 19 .ericburke.set cascade="save-update" inverse="true" * lazy="true" * @hibernate.class table="Categories" */ public class Category extends NameDescription { /** * @hibernate.collection-one-to-many * class="com.[ Xdoclet Tag Example ] /** * @hibernate.collection-key column="parentCategoryId" * @hibernate.linkblog.

hibernate.xml"/> </session-factory> </hibernate-configuration> April 14. or use Spring's XML file ] <hibernate-configuration> <session-factory> <property name="dialect"> net.sf.hsqldb.url"> jdbc:hsqldb:hsql://localhost/linkblog</property> <property name="connection.xml Generated by XDoclet.driver_class"> org.username">sa</property> <property name="connection.HSQLDialect</property> <property name="show_sql">true</property> <property name="use_outer_join">false</property> <property name="connection.cfg.[ hibernate.hbm.jdbcDriver</property> <property name="connection. 2005 Hibernate in 60 Minutes 20 .dialect.pool_size">5</property> <mapping resource="com/ericburke/linkblog/model/Category.xml"/> <mapping resource="com/ericburke/linkblog/model/Resource.hbm.

[   Ant Buildfile Invokes XDoclet ○ ○ ] XDoclet ships with the Hibernate tasks Generates mapping files and hibernate.class files in the taskdef's classpath Hibernate includes tasks for ○ ○  Classpath needs ○ Hibernate Jars.xml hbm2java – generates the persistent classes hbm2ddl – generates the database Requires the persistent .cfg. XDoclet. 2005 . Hibernate extensions. JDBC driver JAR file Hibernate in 60 Minutes 21 April 14.

get().cfg.  APIs to begin/commit/rollback transactions Hibernate in 60 Minutes 22 April 14.set(s). 2005 .buildSessionFactory().xml") .[   HibernateUtil Trivial examples show this class ○ ] Creates a SessionFactory in the static initializer Configuration cfg = new Configuration().configure("/hibernate. if (s == null) { s = sessionFactory. threadSession. SessionFactory sessionFactory = cfg. Provides access to a Session ThreadLocal public static Session getSession() { Session s = (Session) threadSession.openSession(). } return s.

2005 . walk the graph using normal Java collections semantics  Locating persistent objects ○ ○ Detached objects can be challenging Hibernate in 60 Minutes 23 April 14.[   DAOs ] Insulate your code from Hibernate specifics  CRUD operations ○ ○ I use Java 5 generics heavily You can also use Spring for DAO support Use Hibernate queries for efficiency From there.

[ Servlet Filter public void destroy() { } ] public class HibernateFilter implements Filter { public void init(FilterConfig fc) throws ServletException { } } public void doFilter(ServletRequest req. } finally { page 304 HibernateUtil. HibernateUtil.closeSession(). 2005 Hibernate in 60 Minutes 24 . ServletResponse res. FilterChain filterChain) throws IOException. ServletException { try { filterChain. Hibernate in Action.commitTransaction(). res).doFilter(req. } } April 14.

2005 .[    Business Objects A layer between your application code and the DAOs ○ ○ ] Only allow business objects to hit the DAOs Business objects and app code use persistent objects try/catch/finally for transactions Sometimes business object methods just delegate Hibernate in 60 Minutes 25 Provide a consistent place to use AOP ○ Risk duplicating DAO code ○ April 14.

2005 Hibernate in 60 Minutes 26 .[ AOP for Transactions Application Code Architecture Summary ] Database Business Objects DAOs Hibernate Persistent Objects XML Mappings Keep an Open Session April 14.

[   Gotchas Must always have an open session ○ ○ ○ ] Seemingly innocent code like fetching a lazy collection bombs Swing – open a session on event thread Servlets – use a filter or Spring No failonerror attribute Watch the build output carefully Hibernate tasks do not abort Ant ○ ○  Test associations and collections heavily Hibernate in 60 Minutes 27 April 14. 2005 .

181 “Hibernate in Action” You might exhaust available heap space  ?? April 14. 2005 Hibernate in 60 Minutes 28 .[   When Not to Use Hibernate A horrible database design is forced on you ○ ] Many composite keys If your application is mostly mass operations ○ ○ See pg.

Dynamic UPDATE 6.[ 10 Reasons to Love Hibernate ] 1. 2005 Hibernate in 60 Minutes 29 .Optimistic Locking 5.Traversing 10.Trying new databases 9.Query result paging which columns 8.Good price 3.No more DTOs generation – figure out 7.ID generation April 14.Automatic dirty changed checking 2.Good documentation associations 4.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->