1 / 37

Hibernate Basics

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.

jude
Download Presentation

Hibernate Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Hibernate Basics 廖峻鋒 Sep 14,2004 NTU Dept. of CSIE

  2. 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

  3. 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.

  4. 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…

  5. 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

  6. 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.

  7. 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 ?

  8. “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

  9. 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)

  10. Hibernate Architecture

  11. 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

  12. Core Interfaces • Session • SessionFactory • Configuration • Query and Criteria

  13. 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).

  14. SessionFactory • Heavy weight, intended to be shared among threads – typically single SessionFactory for whole application. • One SessionFacotry per Database.

  15. Configuration • Specify the location of mapping document. • Store hibernate properties. • Create SessionFactory. Configuration cfg = new Configuration(); cfg.addClacc(UserInfo.class); SessionFactory factory = cfg.buildSessionFactory();

  16. 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.

  17. Implementation (for new Application) • Write mapping document. • Generate class files and create tables (using Ant) • Set hibernate.properties. • Implement access code with DAO pattern.

  18. Implementation (if tables pre-exist) • Write class files. • Write mapping document. • Set hibernate.properties. • Implement access code with DAO pattern.

  19. Persistence Class in Hibernate • JavaBean specification (or POJOs) • No-arg constructor • Accessor methods for properties

  20. A quick example public class PersistableMessage { private Integer id; private String text; private PersistableMessage next; …(getter and setter methods)… }

  21. Hibernate.properties • Should be put in the classpath. • Connection pool • hibernate 內建support 三種connection pool : • C3p0, apache DBCP, and Proxool

  22. 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>

  23. ID generating strategies

  24. 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)

  25. 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”

  26. Criteria Queries Criteria criteria = session.createCriteria(PersistableMessage.class); criteria.add(Expression.eq("id", Integer.valueOf("1"))); PersistableMessage result = (PersistableMessage) criteria.uniqueResult();

  27. demo • Code generation with hbm2java • Auto-import with hbm2ddl • Client code • Test add message with transaction

  28. Fine-grained Persistence • “More classes than tables” • Fine-grained object models are good • Greater code reuse • More typesafe • Better encapsulation

  29. 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.

  30. Inheritance Mapping

  31. Three ways to map Inheritance • Single Table Inheritance • Concrete Table Inheritance • Class Table Inheritance

  32. Single Table Inheritance • Map all the classes of an inheritance hierarchy to a single table

  33. Single Table Inheritance in Hibernate • 以discriminator欄位區分是那一個子類別 • 在父類別中定義discriminator • 在子類別中定義discriminator value

  34. Fine-grained object model : An example • A more complex example : CACS membership management system.

  35. Topics not covered • Advanced associations mapping • Transaction / concurrency

  36. Mapping Association • One-to-one • Many-to-one • One-to-many • Unidirectional / bidirectional

  37. Q&A

More Related