Introduction To Hibernate

Presented by Ryan Bohn and John Stein Versatile, Inc.

From the data center to users on the move, Versatile turns data into knowledge.
(c) Versatile Systems, Inc.

Agenda ‡ The problem with programming to relational databases ‡ The problem with EJB2 persistence ‡ What is Hibernate and how does it solve these problems? ‡ Where to get Hibernate ‡ Hibernate ORM
± Ways To Map: ‡ XML Mappings ‡ Annotations ± Types of mappings: ‡ basic - one-to-many / many-to-one / many-to-many/ one-to-one

From the data center to users on the move, Versatile turns data into knowledge.
(c) Versatile Systems, Inc.

Agenda (continued) ‡ Hibernate basics
± The Session ± Operations: ‡ load, save, delete

‡ Hibernate queries
± ± ± ± HQL Criteria queries Query by example Native queries

‡ ‡ ‡ ‡

Hibernate and Transactions Lazy loading Alternatives to Hibernate Q&A
From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.

Problem Programming to Relational DBs

From the data center to users on the move, Versatile turns data into knowledge.
(c) Versatile Systems, Inc.

(c) Versatile Systems. Inc. . aggregating ‡ Sharing ± Concurrency (Transactions) ± Many applications ‡ Integrity ± Constraints ± Transaction isolation From the data center to users on the move. sorting ‡ Work with sets of data ± Joining.What do relational DBs do well? ‡ Work with large amounts of data ± Searching. Versatile turns data into knowledge.

but: ‡ Very database specific ‡ Very coupled with the data.What do relational DBs do badly? ‡ Modeling ± No polymorphism / inheritance ± No support for automatic conversion to objects ‡ Business logic ± There¶s stored procedures. . really belongs in the application domain ‡ Transaction ± No concept of application level transactions From the data center to users on the move. Inc. Versatile turns data into knowledge. (c) Versatile Systems.

Problem with EJB From the data center to users on the move. (c) Versatile Systems. . Inc. Versatile turns data into knowledge.

(c) Versatile Systems. Inc. .EJB the answer? ‡ EJB spec tried to bridge the gap between programming and interacting with relational dbs ‡ EJB provides: ± Basic persistence (CMP) ± Method-level transaction management ± Automatic management of associations ± EJBQL provides a very basic object query language From the data center to users on the move. Versatile turns data into knowledge.

ejb ± Interface / Implementation required but do we really need interfaces of our entity beans ± Complex deployment descriptors ± Weird combo of checked / unchecked exceptions ‡ No Polymorphism ‡ Can¶t Test Outside Container ± For example. Inc. Versatile turns data into knowledge. in JUnit ± Why not? ‡ Home is an interface ‡ Relationships/instantiation done by container From the data center to users on the move. .Problems with EJB ‡ Noisy Programming model ± Inheritance from javax. (c) Versatile Systems.

Versatile turns data into knowledge. .Problems with EJB (continued) ‡ EJBQL too limited ± none of: ± Aggregation/projection for reporting ± Outer-join fetching ± Pagination ± Dynamic queries From the data center to users on the move. (c) Versatile Systems. Inc.

Inc. (c) Versatile Systems. . Versatile turns data into knowledge.The Hibernate Solution From the data center to users on the move.

The Hibernate Solution ‡ Hibernate is a persistence framework aimed at solving the shortcomings presented by EJB2. } From the data center to users on the move. public class Book { private Author author. public Author getAuthor()« public void setAuthor(«. (c) Versatile Systems. Inc. ‡ Persistence classes (entities) are POJOs ± Easy to write and refactor ± Can be serialized ± Can execute outside of the container (JUnit) ± Eg. Versatile turns data into knowledge. .

Inc. .The Hibernate Solution (cont. Versatile turns data into knowledge.) ‡ POJO programming model ± Persistent properties are not abstract ± Can instantiate POJOS using new() ± Detached from persistence layer ‡ No Home Interface ± Generic Session interface is provided for persistence operations ± May write own DAO ‡ No method-level transactions for entities ± Rather emphasize transactions at the business level From the data center to users on the move. (c) Versatile Systems.

.The Hibernate Solution (cont.) ‡ Truly object-oriented ± Polymorphic associations and queries ± Three inheritance mapping strategies From the data center to users on the move. (c) Versatile Systems. Inc. Versatile turns data into knowledge.

hibernate. dom4j.Where to get Hibernate ‡ http://www. cglib From the data center to users on the move.org ± ± ± ± ± Download Jar Source code Javadoc Reference documentation Support forums ‡ Requirements ± JDK 1. Versatile turns data into knowledge. Inc.4 or later ± Ehcache. antlr. asm. commons collections. . (c) Versatile Systems. commons logging.

Versatile turns data into knowledge. Inc. (c) Versatile Systems.Hibernate ORM From the data center to users on the move. .

BID } BID_ID ITEM_ID AMT int8 int8 int4 ± Eg. From the data center to users on the move.Hibernate ORM ‡ ORM = Object Relational Mapping: way of telling the container (Hibernate) how to map tables and columns to entity beans public class AuctionItem { AUCTION_ITEM private Long id. DESC varchar(100) private Set bids. Versatile turns data into knowledge. . Inc. (c) Versatile Systems. ITEM_ID int8 private String description.

Hibernate ORM with XML ‡ Hibernate supports mappings via XML: <class name=³AuctionItem´ table=³AUCTION_ITEM´> <id name=³id´ column=³ITEM_ID´> <generator class=³native´/> </id> <property name=³description´ column=³DESCR´/> <set name=³bids´ cascade=³all´ lazy=³true´> <key column=³ITEM_ID´/> <one-to-many class=³Bid´/> </set> </class> XML is yucky! From the data center to users on the move. Versatile turns data into knowledge. (c) Versatile Systems. Inc. .

Hibernate ORM with EJB3 annotations ‡ Hibernate 3 supports ORM via annotations. Advantages are: ± Compatible with EJB3 ± Keeps mapping with the entity ± No XML sit-ups ‡ Disadvantage: ± Java 5 required ‡ So what does AuctionItem look like in the annotated version From the data center to users on the move. Inc. (c) Versatile Systems. Versatile turns data into knowledge. .

. nullable = false) public Long getId() {«} @Column(name = ³DESC´. @Id @Column(name = ³ITEM_ID´. nullable = false) public String getDescription {«} @OneToMany(mappedBy = ³item´) public Set<Bid> getBids {«} } Example From the data center to users on the move.Hibernate ORM with Annotations @Entity @Table(name = ³AUCTION_ITEM´) public class AuctionItem { private Long id. (c) Versatile Systems. Versatile turns data into knowledge. private Set<Bid> bids. private String description. Inc.

allows null. by default uses databases native id generator (auto-increment. etc.Available Annotations ‡ @Entity ± tells Hibernate Persist Me! ‡ @Table ± basic table info such as name ‡ @Id ± Marks the getter as primary key. Versatile turns data into knowledge. . sequences. Inc. etc.) ‡ @Column ± generic information about the column (name.) ‡ @OneToOne ± maps a one-to-one relationship between 2 tables ‡ @OneToMany / @ManyToOne ‡ @ManyToMany ± association table From the data center to users on the move. (c) Versatile Systems. length.

Inc.Available Annotations ‡ @Inheritence ± Three strategies ‡ Table per class ‡ Table per class hierarchy ‡ Joined subclass ‡ Many more annotations! From the data center to users on the move. (c) Versatile Systems. Versatile turns data into knowledge. .

Versatile turns data into knowledge. (c) Versatile Systems. . Inc.Basic Persistence Operations From the data center to users on the move.

hibernate.openSession(). which is retrieved through a SessionFactory ‡ Loading an object by its id long itemId = 500. Inc. itemId). . (c) Versatile Systems. From the data center to users on the move.Session . Versatile turns data into knowledge.Basic Persistence Operations ‡ All persistence operations are done through org. Session session = sessionFactory. AuctionItem item = (AuctionItem) session.class.get(AuctionItem.

// not always necessary ‡ For fun. Versatile turns data into knowledge.save(item) ‡ Updating a row item. session.Basic Persistence Operations ‡ Creating a new row in the database AuctionItem item = new AuctionItem(). let¶s see equivalent operations in JDBC From the data center to users on the move. (c) Versatile Systems. item.setDescription(³Old Chair´). session. Inc.setDescription(³Antique Chair´). .update(item).

.JDBC get Connection conn = DriverManager. . } // we did not even cover getting // the associated entities!!! example From the data center to users on the move. (c) Versatile Systems.executeQuery(). Versatile turns data into knowledge. while (rs. stmt = conn. auction. . .next) { Auction auction = new Auction().getString(³name´)).prepareStatement(sql). ResultSet rs = stmt. Inc.getConnection(«) String sql = ³SELECT * FROM auction´.setName(rs.

(c) Versatile Systems.Querying objects in Hibernate From the data center to users on the move. . Inc. Versatile turns data into knowledge.

(c) Versatile Systems. Inc. .Hibernate Querying ‡ Hibernate several ways to query for objects ± ± ± ± HQL ± Hibernate Query Language Criteria Queries Query by Example Native SQL Queries From the data center to users on the move. Versatile turns data into knowledge.

Versatile turns data into knowledge. (c) Versatile Systems. Inc. . avg) and grouping ± Ordering ± Subqueries ± SQL function calls From the data center to users on the move.Hibernate Query Language ‡ Make SQL be object oriented ± Classes and properties instead of tables and columns ± Polymorphism ± Associations ± Much less verbose than SQL ‡ Full support for relational operations ± Inner/outer/full joins. cartesian products ± Projection ± Aggregation (max.

From the data center to users on the move.Hibernate Query Language Simplest HQL Query: from AuctionItem i. (c) Versatile Systems. Versatile turns data into knowledge. get all the AuctionItems: List allAuctions = session. .e. Inc.list().createQuery(³from AuctionItem´) .

Versatile turns data into knowledge.description like :desc and bid. Inc.Hibernate Query Language More realistic example: select item from AuctionItem item join item.amount > 100 :desc is a named parameter From the data center to users on the move.bids bid where item. (c) Versatile Systems. .

bids bid where bid.amount > 100 order by bid. Versatile turns data into knowledge. Inc.Hibernate Query Language Projection: select item. (c) Versatile Systems. .amount from AuctionItem item join item.description. bid.amount desc From the data center to users on the move.

Inc. Versatile turns data into knowledge.amount).type order by max(bid. (c) Versatile Systems. .amount) From the data center to users on the move.bids bid group by item.Hibernate Query Language Aggregation: select max(bid. count(bid) from AuctionItem item left join item.

(c) Versatile Systems.Criteria Queries Criteria queries provide: . .suited well for dynamic queries .extensible From the data center to users on the move.way of generating queries through method calls . Versatile turns data into knowledge. Inc.

(c) Versatile Systems. minAmount) ) .add( Expression. Equivalent HQL: from AuctionItem item left join fetch item.amount > :minAmount From the data center to users on the move.createCriteria(³successfulBid´) . Inc.add( Expression.bids where item. FetchMode.gt(³amount´.successfulbid. Versatile turns data into knowledge.EAGER) .createCriteria(AuctionItem.description like :description and item.Criteria Queries List auctionItems = session.list().setFetchMode(³bids´.class) . description) ) . .like(³description´.

createCriteria(³bids´) .0). .create(item).setDescription(³hib´).ST ART) ) .create(bid) ) .add( Example.Hibernate Querying ‡ Query By Example: AuctionItem item = new AuctionItem(). bid.createCriteria(AuctionItem.enableLike(MatchMode.class) . Versatile turns data into knowledge.setAmount(1. Bid bid = new Bid(). List auctionItems = session. Inc.list().add( Example. item. EXAMPLE From the data center to users on the move. (c) Versatile Systems.

Transactions in Hibernate From the data center to users on the move. Inc. (c) Versatile Systems. Versatile turns data into knowledge. .

. throw e. Here¶s an example: Session session = sf. } catch (Exception e) { tx.getBids().add(bid).class. bid.rollback(). item.openSession(). try { AuctionItem item = (AuctionItem) session. Transaction tx = session.Hibernate Transactions ‡ Like other operations. tx.commit(). Inc. (c) Versatile Systems. transactions are performed using the Session object.get(ActionItem.setItem(item).close(). itemId). } From the data center to users on the move. Versatile turns data into knowledge.beginTransaction(). } finally { session.

Hibernate Transactions ‡ Some advice . calling a setter could automatically go back to the database From the data center to users on the move. . Versatile turns data into knowledge. (c) Versatile Systems.Wrap all write operations in a transaction. Otherwise. Inc.

(c) Versatile Systems.Lazy Loading From the data center to users on the move. . Versatile turns data into knowledge. Inc.

but it doesn¶t load bids until the first call ‡ Accomplished with dynamic proxies using CGLIB ‡ Can change by setting fetchmode on a column mapping ‡ Be wary of this if passing object to view after session has been closed From the data center to users on the move.Lazy Loading ‡ By default all one-to-many associations don¶t get fetched immediately. . Versatile turns data into knowledge. (c) Versatile Systems. load an AuctionItem. For example. Inc.

(c) Versatile Systems. Inc. . Versatile turns data into knowledge.Alternatives to Hibernate From the data center to users on the move.

(c) Versatile Systems. Versatile turns data into knowledge. most likely Hibernate will be an implementation of EJB3 persistence ± JBOSS does this today! From the data center to users on the move.Alternatives to Hibernate ‡ ‡ ‡ ‡ Oracle Toplink Ibatis JDO Many more ‡ EJB3 ± not really. Inc. .

(c) Versatile Systems.Q&A From the data center to users on the move. Inc. . Versatile turns data into knowledge.

Sign up to vote on this title
UsefulNot useful