Top Banner
Hibernate: the short version Björn Granvik, Jayway
22

Hibernate 2005

Jun 29, 2015

Download

Technology

Björn Granvik

Introduction to the object to relational mapping framework called Hibernate.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Hibernate 2005

Hibernate: the short version

Björn Granvik, Jayway

Page 2: Hibernate 2005

Overview

• Dry run: Theory• Wet run: Lab

– Tutorial part 1: Store two tables with straight Hibernate and do the same using Spring.

– Tutorial part 2: More relationships

Page 3: Hibernate 2005

Write the SQL

CREATE TABLE users (

LogonID varchar(20) NOT NULL default 0,

Name varchar(40) default NULL,

Password varchar(20) default NULL,

EmailAddress varchar(40) default NULL, LastLogon datetime default NULL,

PRIMARY KEY (LogonID)

);

Page 4: Hibernate 2005

Create the Pojo

public class User {private String userID;private String userName;private String password;...public String getID() {

return userID;}public void setID(String newUserID) {

userID = newUserID;}...

}

Page 5: Hibernate 2005

Write the hbm file

<hibernate-mapping>

<class name=”dbdemo.User" table="users">

<id name="ID" column="LogonId" type="string">

<generator class=”native"/>

</id>

<property name="userName"

column="Name” type="string"/>

<property name="password" type="string"/>

<property name="emailAddress" type="string"/>

<property name="lastLogon" type=”java.util.Date"/>

</class>

</hibernate-mapping>

Page 6: Hibernate 2005

Property file

hibernate.connection.driver_class=org.gjt.mm.mysql.Driver

hibernate.connection.url=jdbc:mysql://localhost/testdb

hibernate.connection.username = gsmith

hibernate.connection.password = sesame

...

caches etc

Page 7: Hibernate 2005

So far

• User.java - Java bean object to persist • User.hbm.xml - Hibernate mapping file • hibernate.properties - properties file with JDBC

connection info• SQL User table in your database

Page 8: Hibernate 2005

What to do

• Create a Pojo• Tell the DB about the type of objects you want to

store • Create a Session to your database of choice • Load, Save and Query your objects • flush() your Session back to the database

Page 9: Hibernate 2005

Example: Setup

// Set up configuration

... conf

// Then build a session to the database

SessionFactory sf = conf.buildSessionFactory();

session = sf.openSession();

Page 10: Hibernate 2005

Example: Save

// Create new User and store it in db

User newUser = new User();

newUser.setID("joe_cool");

newUser.setUserName("Joseph Cool");

...

// And call Hibernate to store it

session.save(newUser);

Page 11: Hibernate 2005

Example: Get single user

User newUser = (User)session.load(User.class, suserId);

Page 12: Hibernate 2005

Example: Get users

List myUsers = session.find("from User");

for (Iterator i = myUsers.iterator(); i.hasNext();) {

User nextUser = (User) i.next();

System.out.println("Resetting password for User: "

+ nextUser.getUserName());

nextUser.setPassword("secret");

}

...

Page 13: Hibernate 2005

Example: flush

// close our session and release resources

session.flush();

session.close();

Page 14: Hibernate 2005

OR vs. Relational model

• Java object identity, equality, primary keysa == b

a.equals(b)

• Polymorphism• Joining tables vs. navigating associations

– (bi)birectional relations

• Detach

Page 15: Hibernate 2005

Detached objects

Retrieve an AuctionItem and change the description:

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();AuctionItem item =

(AuctionItem) session.get(ActionItem.class, itemId);tx.commit();session.close();

Bid bid = new Bid();bid.setAmount(bidAmount);bid.setItem(item);item.getBids().add(bid);

Session session2 = sessionFactory.openSession();Transaction tx = session2.beginTransaction();session2.update(item);tx.commit();session2.close();

Page 16: Hibernate 2005

One-to-One

Java usage:

Bar myBar = Foo.getBar();

Mapping file: Mapping file:

<class name=“Foo”>

...

<one-to-one name=“bar” class=“Bar” />

</class>

Schema:

Foo Bar

id id

Page 17: Hibernate 2005

One-to-Many

Java usage:

Set myBars = Foo.getBars();

Mapping file: Mapping file:

<class name=“Foo”> ”>

...

<set role=“bars” table=“bar” inverse=“true”>

<key column=”foo_id” />

<one-to-many class=“Bar”>

</set>

</class>

Schema:

Foo Bar

id id, foo_id

Page 18: Hibernate 2005

One-to-Many

Java usage:Set myBars = Foo.getBars();

Mapping file: Mapping file:<class name=“Foo”> ”>...

<set role=“bars” table=“bar” inverse=“true” lazy=“true” cascade=”orphan-delete”>

<key column=”foo_id” /><one-to-many class=“Bar”>

</set></class>

Schema:Foo Barid id, foo_id

Page 19: Hibernate 2005

Many-to-Many

Java usage:

Set myBars = Foo.getBars();

Mapping file: Mapping file:

<class name=“Foo”> ”>

...

<set role=“bars” table=“Foo_Bar”>

<key column=”foo_id” />

<many-to-many column=“bar_id” class=“Bar”>

</set>

</class>

Schema:

Foo Bar Foo_Bar

id id foo_id, bar_id

No relationalclass FooBar!

Page 20: Hibernate 2005

Much more

• Criteria• Query by example• Composites

• Version 3.0

Page 21: Hibernate 2005

CriteriaList cats = sess.createCriteria(Cat.class)

.add( Expression.like("name", "Fritz%") )

.add( Expression.between("weight",

minWeight, maxWeight) )

.list();

Page 22: Hibernate 2005

Query by exampleExample example = Example.create(cat

.excludeZeroes() //exclude zero valued properties

.excludeProperty("color") //exclude the property "color"

.ignoreCase(

.enableLike(); //use like for string comparisons

List results = session.createCriteria(Cat.class)

.add(example)

.list();