Java Data Persistence Using HibernateOverviewWhat is Hibernate?What is Object/Relational Mapping?Create ExampleRead ExamplesPersistable ClassesDatabase TableMapping Class to TableConfigurationConfiguration PropertiesSessionTransactionObject LifecycleQuery OptionsAssociationsOne-to-Many Example: UnidirectionalOne-to-Many Example: BidirectionalOne-to-Many Table StructureSlide 20Many-to-Many Example: UnidirectionalMany-to-Many Example: BidirectionalMany-to-Many Table StructureSlide 24ReferencesJava Data Persistence Using HibernateJack GardnerOctober 20042OverviewWhat is HibernateWhat is ORMCreate ExampleRead ExamplesPersistable ClassesDatabase TableMapping Class to TableConfigurationConfiguration PropertiesSessionTransactionObject LifecycleQuery OptionsAssociationsReferences3What is Hibernate?An object/relational mapping (ORM) implementationOpen sourceDevelopment started late 20014What is Object/Relational Mapping?Provides a transparent bridge between objects and database tablesAllows source code to work with objects and their attributes vs. tables and columnsEliminates need for most/all SQLEliminates use of query result sets5Create Example// create a new objectWidget w = new Widget();w.setName(“WidgetA”);w.setValue(10);// persist itsession.save(w);6Read Examples// get a known widgetWidget w = (Widget) session.load(Widget.class, “WidgetA”);// get all widgetsList widgets = session.find(“from Widget”);7Persistable ClassesClasses are simply JavaBeanspublic class Widget{private String name;private int value;public Widget() {}public String getName() {return name;}public void setName(String s) {name = s;}public int getValue() {return value;}public void setValue(int i) {value = i;}}8Database TablePersistable classes have an associated table9Mapping Class to Tablewidget.hbm.xml<hibernate-mapping><class name=“mypackage.Widget” table=“WIDGET”> <id name=“name” column=“NAME”> <generator class=“assigned”/></id><property name=“value” column=“VALUE”/></class></hibernate-mapping>10Configurationimport net.sf.hibernate.cfg.Configuration;import net.sf.hibernate.SessionFactory;// build configuration based on propertiesConfiguration config = new Configuration();// add persistable classes to configurationconfig.addClass(Widget.class);// build a session factory based on configurationSessionFactory sessionFactory = config.buildSessionFactory();11Configuration Propertieshibernate.propertieshibernate.dialect=net.sf.hibernate.dialect.Oracle9Dialecthibernate.connection.driver_class=oracle.jdbc.driver.OracleDriverhibernate.connection.url=jdbc:oracle:thin:@oracle.cis.ksu.edu:1521:ORACLEhibernate.connection.username=<myusername>hibernate.connection.password=<mypassword>12SessionLightweight and inexpensive to create/destroyNot threadsafe – each thread needs its ownObtained from SessionFactory instanceSession session = sessionFactory.openSession();// perform persistence operationssession.close();13TransactionSet of operations that are all committed or all rolled backObtained from Session instanceCan perform multiple transactions within sessionTransaction tx = session.beginTransaction();// perform persistence operationstx.commit();14Object LifecycleTransientNewly created objectPersistentNew object has been “saved”Previously saved object has been “read”DetachedSession closedPersistent object serializedCan be reattached later to become persistent15Query OptionsHibernate Query Language (HQL)Query q = session.createQuery(“from Widget w where w.value > :value”);q.setParameter(“value”, someValue);List widgets = q.list();Criteria APICriteria c = session.createCriteria(Widget.class);c.add(Expression.gt(“value”, someValue);List widgets = c.list();SQLQuery q = session.createSQLQuery(“select {w.*} from WIDGET {w} where VALUE > :value”, “w”, Widget.class);q.setParameter(“value”, someValue);List widgets = q.list();16AssociationsSupports all association typesone-to-oneone-to-manymany-to-manyInherently unidirectionalSupports bidirectional17One-to-Many Example: UnidirectionalOption 1: Group Memberpublic class Group public class Member{ { private String name; private String name; private Collection members; … … }}Option 2: Group Memberpublic class Group public class Member{ { private String name; private String name; … private Group group;} …}18One-to-Many Example: BidirectionalGroup Memberpublic class Group public class Member{ { private String name; private String name; private Collection members; private Group group; … …} }Application responsible for maintaining each end of association19One-to-Many Table StructureUnderlying table structure not affected by directionalityStandard implementationForeign key in many-side tableAlternate implementationUse join table, with no-duplicate constraint on many-side foreign key20One-to-Many Table Structure21Many-to-Many Example: UnidirectionalOption 1: Group Memberpublic class Group public class Member{ { private String name; private String name; private Collection members; … … }}Option 2: Group Memberpublic class Group public class Member{ { private String name; private String name; … private Collection groups;} …}22Many-to-Many Example: BidirectionalGroup Memberpublic class Group public class Member{ { private String name; private String name; private Collection members; private Collection groups; … …} }Application responsible for maintaining each end of association23Many-to-Many Table StructureUnderlying table structure not affected by directionalityImplemented using join table24Many-to-Many Table Structure25ReferencesBauer, Christian and Gaven King, Hibernate in Action, Manning, 2005.Hibernate Reference Documentation, Version 2.1.6, Hibernate,
View Full Document