Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Hibernate 2005


Published on

Introduction to the object to relational mapping framework called Hibernate.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Hibernate 2005

  1. 1. Hibernate:the short versionBjörn Granvik, Jayway
  2. 2. Overview• Dry run: Theory• Wet run: Lab– Tutorial part 1: Store two tables with straight Hibernateand do the same using Spring.– Tutorial part 2: More relationships
  3. 3. Write the SQLCREATE 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));
  4. 4. Create the Pojopublic class User {private String userID;private String userName;private String password;...public String getID() {return userID;}public void setID(String newUserID) {userID = newUserID;}...}
  5. 5. 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>
  6. 6. Property = gsmithhibernate.connection.password = sesame...caches etc
  7. 7. So far• - Java bean object to persist• User.hbm.xml - Hibernate mapping file• - properties file with JDBCconnection info• SQL User table in your database
  8. 8. What to do• Create a Pojo• Tell the DB about the type of objects you want tostore• Create a Session to your database of choice• Load, Save and Query your objects• flush() your Session back to the database
  9. 9. Example: Setup// Set up configuration... conf// Then build a session to the databaseSessionFactory sf = conf.buildSessionFactory();session = sf.openSession();
  10. 10. Example: Save// Create new User and store it in dbUser newUser = new User();newUser.setID("joe_cool");newUser.setUserName("Joseph Cool");...// And call Hibernate to store;
  11. 11. Example: Get single userUser newUser = (User)session.load(User.class, suserId);
  12. 12. Example: Get usersList myUsers = session.find("from User");for (Iterator i = myUsers.iterator(); i.hasNext();) {User nextUser = (User);System.out.println("Resetting password for User: "+ nextUser.getUserName());nextUser.setPassword("secret");}...
  13. 13. Example: flush// close our session and release resourcessession.flush();session.close();
  14. 14. OR vs. Relational model• Java object identity, equality, primary keysa == ba.equals(b)• Polymorphism• Joining tables vs. navigating associations– (bi)birectional relations• Detach
  15. 15. Detached objectsRetrieve 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();
  16. 16. One-to-OneJava usage:Bar myBar = Foo.getBar();Mapping file: Mapping file:<class name=“Foo”>...<one-to-one name=“bar” class=“Bar” /></class>Schema:Foo Barid id
  17. 17. One-to-ManyJava 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 Barid id, foo_id
  18. 18. One-to-ManyJava 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
  19. 19. Many-to-ManyJava 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_Barid id foo_id, bar_idNo relationalclass FooBar!
  20. 20. Much more• Criteria• Query by example• Composites• Version 3.0
  21. 21. CriteriaList cats = sess.createCriteria(Cat.class).add("name", "Fritz%") ).add( Expression.between("weight",minWeight, maxWeight) ).list();
  22. 22. Query by exampleExample example = Example.create(cat.excludeZeroes() //exclude zero valued properties.excludeProperty("color") //exclude the property "color".ignoreCase(.enableLike(); //use like for string comparisonsList results = session.createCriteria(Cat.class).add(example).list();