hibernate 2005
DESCRIPTION
Introduction to the object to relational mapping framework called Hibernate.TRANSCRIPT
Hibernate: the short version
Björn Granvik, Jayway
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
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)
);
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;}...
}
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>
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
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
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
Example: Setup
// Set up configuration
... conf
// Then build a session to the database
SessionFactory sf = conf.buildSessionFactory();
session = sf.openSession();
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);
Example: Get single user
User newUser = (User)session.load(User.class, suserId);
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");
}
...
Example: flush
// close our session and release resources
session.flush();
session.close();
OR vs. Relational model
• Java object identity, equality, primary keysa == b
a.equals(b)
• Polymorphism• Joining tables vs. navigating associations
– (bi)birectional relations
• Detach
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();
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
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
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
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!
Much more
• Criteria• Query by example• Composites
• Version 3.0
CriteriaList cats = sess.createCriteria(Cat.class)
.add( Expression.like("name", "Fritz%") )
.add( Expression.between("weight",
minWeight, maxWeight) )
.list();
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();