1 / 110

Hibernate Quick Start

Hibernate Quick Start. Justin PS. Agenda. O/R Mapping Concepts Introduce example data model O/R mapping with hibernate Basic O/R Mapping Advanced O/R Mapping Hibernate Query Language (HQL) Native Query Interactive HQL execution Hibernate performance tuning

lucien
Télécharger la présentation

Hibernate Quick Start

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 Quick Start Justin PS

  2. Agenda • O/R Mapping Concepts • Introduce example data model • O/R mapping with hibernate • Basic O/R Mapping • Advanced O/R Mapping • Hibernate Query Language (HQL) • Native Query • Interactive HQL execution • Hibernate performance tuning • Hibernate and Junco integration • Speedup Hibernate Development with Middlegen

  3. Objectives • Introduce basic knowledge of: • O/R ABC • Basic Hibernate • Hibernate Query Language (HQL) • Hibernate tools • Share experience with Hibernate

  4. Object-Orientation & Rational Database • In most business application, object-oriented technology is used to write application, but data are stored in rational database • Object-Orientation is good at encapsulation, reuse and adaptive to change • Rational database excels in data manipulation, sort, search, batch update & insert

  5. Object-Rational Impendence Mismatch • Object is described by Class, properties • Database is described by table, fields • Objects are related to each other by association & reference • Tables are related to each other by join • Object contains both data and behaviors • Behaviors are provided by trigger or stored procedure separately • Object-Orientation place emphasis on fast development • Rational database emphasize on efficient storage and fast retrieval of data • The object-oriented paradigm is based on proven software engineering principles • The relational paradigm, however, is based on proven mathematical principles

  6. Let there be a bridge… • Translate the semantic in one world into another • Combine both advantages

  7. What is Hibernate • OSS Java object-relational mapping tools • Created by Gavin King (gavin@hibernate.org) • JavaWorld Editor’s Choice for 2003 • 2003 SD magazine Jolt award • Popular: increasing development community (13 000 downloads/month) • Joined JBoss Group (Will be core of JBoss CMP 2.0 engine) • Chinese forum and website available (www.hibernate.org.cn)

  8. Before we have Hibernate • Raw JDBC/SQL-J (labor-intensive, error-prone and not portable) • Standard based JDO, EJB • JDO implementations (immature) • J2EE EJB2.x CMP (complex) • O/R mapping (Lightweight) • Commercial solutions • TopLink • CocoBase • Open source solutions • Castor (not stable)

  9. Features of Hibernate • Transparent persistence (POJO/JavaBeans) • Three basic inheritance mapping strategies • Table per class • Table per concrete class • Table per hierarchy • Powerful query • Projection, aggregation • Sub-query, join • Native query • Smart data retrieval strategies • Lazy fetching • Outer join fetching • Session level and JVM level cache • Pagination • Support versioned data

  10. Features of Hibernate(cont) • Third party rapid development tool support • Modeling tools/code generators • AndroMDA (UML driven development) • Middlegen (Data driven development) • IDE plug-ins: Eclipse, IDEA • XDoclet • Optimized main-stream RDBMS support • Oracle 8i,9i • DB2 7.1, 7.2 • MySQL 3.23 • PostgreSQL 7.x • Sybase12.5 • MS SQL Server 2000

  11. Benefits of Hibernate • Improve developer’s productivity • Code can be tested without container • Classes may be reused in “non-persistent” context • Handy tools (Middlegen, xdoclet, Hibern8IDE) • Minimize LOC • Improve application’s performance • Minimize database access with smart fetching strategies • Opportunities for aggressive caching • Provision for proprietary SQL to enhance batch insert/update efficiency

  12. Example data model Introduction • Let’s introduce part as an example throughout this presentation • And suppose MS SQL Server 2000 is underlying database • Part has • Basic info like id, code, englishName, standardCost • Inventory and turnover data like pt, blevel, ifg, lead time • Supply vendors • Aliases • Currency • Inventory info kept in separate table

  13. Example data model(cont) • Part procurement infos are described by PurchaseOrder and POLine • PurchaseOrder info includes: • supplier, submit time, code, operator • POLine info includes: • ordered part, ordered qty, purchase price, remark • See data diagram on next slide

  14. Part Data Diagram

  15. Purchase Order Diagram

  16. O/R mapping with Hibernate • Hibernate mapping is specified in xml (*.hbm.xml) • Table is mapped to class • Primary key is mapped to object identifier • Columns are mapped to properties • Foreign key is mapped to object reference to other class • One-to-Many and Many-to-Many relations are mapped to collection

  17. Suppose we have an entity Currency with private Long id; private String code; private double rate; private boolean isDefault; Here’s the mapping: Basic Mapping by example

  18. Basic Mapping Steps • Step 1: map table to object • Specify fully qualified java class name • And optionally corresponding table name • Step 2: map primary key to object identifier • Specify if auto key generation is needed • If so give extra info like sequence name • Step 3: map column to object’s property • Specify property name • property type (so-called hibernate type) • And optionally corresponding column name • Repeat step 3 for the rest columns

  19. Object to table mapping syntax

  20. Map identifier to primary key syntax

  21. Auto key generation—Generator details • Supported key generation strategies: • identity: auto-increment column in database like MS SQL Server, Sybase, MySQL • sequence: sequence in database like oracle • hilo: use a table and column (by default hibernate_unique_key and next) to efficiently generate identifiers of type long, short or int, • UUID:A unique string or 32-hex string consists of: • IP address, • startup time of the JVM (accurate to a quarter second), • system time, • counter value (unique within the JVM).

  22. Auto key generation—Generator details • Supported key generation strategies: • native: use identity, hilo or sequence according to capability of underlying database • foreign: use associated object’s id, applicable to one-to-one mapping <id name="id" type="java.lang.Long" column="ID" unsaved-value="null" > <generator class="foreign"> <param name="property">client</param> </generator> </id> <one-to-one name="client" cascade="none" class="com.erry.model.baseinfo.Client"/>

  23. Example for Oracle 8i, 9i

  24. Example for MS SQL Server

  25. Map simple property to column syntax

  26. name—property name in Java class column—column name in database table type—Hibernate data type Map simple property to column

  27. Hibernate Data Type • Basic value type • Numeric Type • integer, long, short, float, double, character, byte, boolean, yes_no, true_false • string • Time Type • date, time, timestamp, calendar, calendar_date • big_decimal • Entity—Persistent Class • Customized Type • Class that implemets net.sf.hibernate.UserType or net.sf.hibernate.CompositeUserType

  28. Suppose we have an entity Vendor with private Long id; private String code; private String name; private int type; private String customType; private int alarmTime; private int leadTime; private String website; private String freightAgent; private int billType; private boolean isFrozen; private boolean isUsed; private boolean isValid; private Currency currency; private Collection contactInfos; Basic Mapping another example

  29. Here’s the mapping: Another example mapping xml

  30. Advanced Mapping • Relationship Mapping • One-to-Many • Many-to-One • Many-to-Many • Customizing the DDL

  31. M:1 Mapping • Many-to-One relation links a many side entity to a one side entity • Simply think of many-to-one relation as a property with entity data type

  32. M:1 Mapping Syntax

  33. Still take Vendor for example, examine property currency: private Long id; private String code; private String name; private int type; private String customType; private int alarmTime; private int leadTime; private String website; private String freightAgent; private int billType; private boolean isFrozen; private boolean isUsed; private boolean isValid; private Currency currency; private Collection contactInfos; Vendor example revisited

  34. Here’s the mapping: M:1 example mapping xml

  35. 1:M Mapping • One-to-Many relation contains a collection of associated entities • Simply treat One-to-Many relation as a property of collection type contains associated entities

  36. 1:M Mapping Syntax

  37. private Long id; private String code; private String englishName; private String localName; private double standardCost; private java.util.Date ifgModifyTime; private boolean isValid; private long blevel; private int leadTime; private int ifg; private long pt; private Currency currency; private Collection partVendors; private Collection partAliases; private Collection replacements; private Collection canReplaceParts; 1:M Mapping Java Source

  38. Mapping source snippet: 1:M Mapping Sample

  39. M:N Mapping • Many-to-Many relation links a many side entity to another many side entity • Simply consider Many-to-Many relation as a property with a collection of entity data

  40. M:N Mapping Syntax

  41. private Long id; private String code; private String englishName; private String localName; private double standardCost; private java.util.Date ifgModifyTime; private boolean isValid; private long blevel; private int leadTime; private int ifg; private long pt; private Currency currency; private Collection partVendors; private Collection partAliases; private Collection replacements; private Collection canReplaceParts; M:N Mapping Java Source

  42. Mapping source snippet M:N Mapping Sample

  43. Customizing the DDL • Hibernate mapping can contains information used only for DDL generation tools like SchemaExport. Specify a column type by using the sql-type attribute of a <column> element. • For instance, you can define a BigDecimal type property ‘amount’ then mapping it to sql-typeNUMERIC(11,2) as following:

  44. Mapping caveat • Although hibernate can guess what table name, column name and data type to use if they are omitted, Always explicitly specify table name, data type and column name! • Hibernate does check the consistency of data type specified in mapping file and the one declared in java class, Always ensure the twos are consistent to avoid some strange problems! • Since writing mapping file manually is inherently error-prone and time-consuming, Always prefer using mapping file auto-generation tools to hand-craft.

  45. Hibernate Query Language • Wrapper of SQL with object-oriented semantics • Classes and properties instead of tables and columns • Polymorphism • Associations • Much less verbose than SQL • Full support for relational operations • Inner/outer/full joins, cartesian products • Projection • Aggregation (max, avg) and grouping • Ordering • Sub-query • SQL function calls

  46. Hibernate Query Language(cont) • Hibernate is capable of creating query from native SQL query • Advantages: • Easy to express complicated search conditions • Easy to use proprietary SQL functions • Disadvantages: • Make application not portable • Named Query/SQL-Query to decouple java code and query statement • Built-in pagination support for various database

  47. HQL basic construct • Case-insensitive: HQL is case-insensitive, except for names of Java classes and properties. • HQL construct: • The select clause • The from clause • The where clause • The order by clause • The group by clause • Associations and joins • Aggregate functions • Expressions

  48. HQL By Example(simplest) • Problem: find all parts whose standard cost is between 10.00 & 1000.00 • Solution: • select p from com.erry.model.part.Part as p where p.standardCost>=10.00 and p.standardCost<=1000.00

  49. HQL By Example(simple join) • Problem: find parts by default vendor and part name • Solution: select p from com.erry.model.part.Part as p inner join p.partVendors as pv where p.isValid=1 and pv.vendor.id=:vendorId • Explanation: string precede with semicolon is HQL named parameter

More Related