380 likes | 577 Views
Hibernate Basics. 廖峻鋒 Sep 14,2004 NTU Dept. of CSIE. What is Persistence ?. Ability of an object to survive even current session or program terminate. Source : W.Keller “ Persistence Options for Object-Oriented Programs ”, JAOO 2003. Object-Relational Mapping.
E N D
Hibernate Basics 廖峻鋒 Sep 14,2004 NTU Dept. of CSIE
What is Persistence ? • Ability of an object to survive even current session or program terminate. Source : W.Keller “Persistence Options for Object-Oriented Programs”, JAOO 2003
Object-Relational Mapping • Automated persistence of object to tables in RDBMS. • Usually with the help of metadata that describes the mapping. • SQL is auto-generated by the metadata description.
ORM Solution • An ORM Solution consists of the following pieces: • Persistence Manager with CRUD API. • Query API • Mapping metadata • Other cross-cutting concerns : transaction, lazy fetching, catching…
ORM Quality [Fussel 97] • Pure relational • 整個應用程式以table-oriented方式來設計 • Light object mapping • Using DAO pattern to hide SQL/JDBC from object model. • Medium object mapping • Simple O-R mapping framework, ex: iBATIS SQLMap • Full object mapping • Supports sophisticated object modeling : composition, inheritance, persistence by reachability, ex : hibernate
Generic ORM Problems (1) • How persistence classes look like ? • 需要extends特殊界面嗎?需要implements serializable嗎?建構子能不能有參數? • How mapping metadata defined ? • How to map inheritance hierarchies ? • How to map object identity, equality as well as database identity.
Generic ORM Problems (2) • How business logic interact with persistence logic ? • How to manage lifecycle of entities ? • How to provide sorting, searching and aggregating ? • How to retrieve data efficiently ?
“Modern” ORM Solutions • Transparent Persistence (POJO/JavaBeans) • Persistent/transient instances • Automatic Dirty Checking • Transitive Persistence • Lazy Fetching • Outer Join Fetching • Runtime SQL Generation • Three Basic Inheritance Mapping Strategies
Hibernate • Open Source (LGPL) • Popular (13 000 downloads/month) • Persistence for JavaBeans • Support for very fine-grained, richly typed object models • Powerful queries (Criteria and HQL)
Four types of Interfaces • Perform or support CRUD and query : Session,Transaction, Query. • Config : SessionFactory, Configuration. • Callback interface : Interceptor, Lifecycle, Validatable. (not covered in this slide) • Extension point : UserType, IdentifierGenerator. (not covered in this slide) Please refer to Hibernate in Action chap 8 for details of callback and extension interfaces
Core Interfaces • Session • SessionFactory • Configuration • Query and Criteria
Session • Persistence Manager of hibernate. • One for each thread – can not be shared, not thread safe. • Light weight– inexpensive to create / destroy. • A cache of loaded objects related to a single unit of work (I.e. a transaction).
SessionFactory • Heavy weight, intended to be shared among threads – typically single SessionFactory for whole application. • One SessionFacotry per Database.
Configuration • Specify the location of mapping document. • Store hibernate properties. • Create SessionFactory. Configuration cfg = new Configuration(); cfg.addClacc(UserInfo.class); SessionFactory factory = cfg.buildSessionFactory();
Hibernate Mapping metadata • One mapping file per class. • Naming convention : (entity class name).hbm.xml • Usually put in the same directory with class files • Otherwise you have to specify metadata files in Configuration using addRecourse() method.
Implementation (for new Application) • Write mapping document. • Generate class files and create tables (using Ant) • Set hibernate.properties. • Implement access code with DAO pattern.
Implementation (if tables pre-exist) • Write class files. • Write mapping document. • Set hibernate.properties. • Implement access code with DAO pattern.
Persistence Class in Hibernate • JavaBean specification (or POJOs) • No-arg constructor • Accessor methods for properties
A quick example public class PersistableMessage { private Integer id; private String text; private PersistableMessage next; …(getter and setter methods)… }
Hibernate.properties • Should be put in the classpath. • Connection pool • hibernate 內建support 三種connection pool : • C3p0, apache DBCP, and Proxool
Writing Metadata <hibernate-mapping> <classname="demo.PersistableMessage" table="MESSAGE"> <idname="id" type="int" column="MSG_ID"> <generator class="native"/> </id> <propertyname="text" type="string" column="MSG_TEXT"/> <many-to-onename="nextMessage" cascade="all" column="NEXT_MSG_ID"/> </class> </hibernate-mapping>
Retrieving Objects • Hibernate Query Language (HQL) • “Minimal” OO dialect of ANSI SQL • CriteriaQueries • Extensible framework for expressing query criteria as objects • Includes “query by example” • Native SQL Queries (NamedQuery)
Hibernate Query Language Example: select item from AuctionItem item join item.bids bid where item.description like ‘hib%’ and bid.amount > 100 i.e. get all the AuctionItems with a Bid worth > 100 and description that begins with “hib”
Criteria Queries Criteria criteria = session.createCriteria(PersistableMessage.class); criteria.add(Expression.eq("id", Integer.valueOf("1"))); PersistableMessage result = (PersistableMessage) criteria.uniqueResult();
demo • Code generation with hbm2java • Auto-import with hbm2ddl • Client code • Test add message with transaction
Fine-grained Persistence • “More classes than tables” • Fine-grained object models are good • Greater code reuse • More typesafe • Better encapsulation
Dependent Mapping • Entity has its own database identity (primary key). • Value is owned by an entity, its lifecycle dependents on owning entity. • Hibernate use <component> to map value type properties.
Three ways to map Inheritance • Single Table Inheritance • Concrete Table Inheritance • Class Table Inheritance
Single Table Inheritance • Map all the classes of an inheritance hierarchy to a single table
Single Table Inheritance in Hibernate • 以discriminator欄位區分是那一個子類別 • 在父類別中定義discriminator • 在子類別中定義discriminator value
Fine-grained object model : An example • A more complex example : CACS membership management system.
Topics not covered • Advanced associations mapping • Transaction / concurrency
Mapping Association • One-to-one • Many-to-one • One-to-many • Unidirectional / bidirectional