Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces.

Similar presentations


Presentation on theme: "Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces."— Presentation transcript:

1 Hibernate Introduction - 1 Present by Eric Yu

2 BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces Configuration Persistent classes Basic O/R mapping Collection mapping Association mapping Component mapping

3 BeanSoft | 3 Understanding O/R persistence What is persistence? Object-oriented applications Relational database system The paradigm mismatch Object/relational mapping What is ORM? Why ORM (solution)? productivity, maintainability performance, vendor independence

4 BeanSoft | 4 Understanding O/R persistence What do RDBS do well? Work with large amounts of data searching, sorting Work with sets of data joining, aggregating Share concurrency, many applications Integrity constraint, transaction isolation What do RDBS do badly? Modeling no polymorphism; fine-gained modeling is difficult Biz logic in stored procedure

5 BeanSoft | 5 Introduction Hibernate Open Source (LGPL) Mature and Popular (15,000 downloads/month) Custom API Will be referred by EJB 3.0 in its redesign of entity beans Features Persistence for POJOs (Plain Ordinary/Old Java Object) Flexible and intuitive mapping Support for fine-grained object models Powerful, high performance queries Two-level Caching Architecture Toolset for roundtrip development Support for detached persistent objects

6 BeanSoft | 6 Architecture Figure 1Figure 2

7 BeanSoft | 7 The core interfaces SessionFactory A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider Session A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Persistent Objects and Collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, Transient and detached Objects and Collections Instances of persistent classes that are not currently associated with a Session. Transaction A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. ConnectionProvider (Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer. TransactionFactory (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.

8 BeanSoft | 8 Configuration Objective Used to build an SessionFactory. Main items JDBC connection / datasource Classes mapping files Diff for managed and non-managed environments Two styles Properties configure file XML configure file (recommended)

9 BeanSoft | 9 Configuration Sample Properties file for Non-managed env XML file for Managed env synnex/jdbc/CISDB org.hibernate.dialect.SybaseDialect org.hibernate.transaction.JTATransactionFactory synnex/jdbc/CISDB org.hibernate.dialect.SybaseDialect org.hibernate.transaction.JTATransactionFactory hibernate.connection.url = \ jdbc:sybase:Tds:192.168.200.11:4500/CIS hibernate.connection.driver_class = \ com.sybase.jdbc2.jdbc.SybDriver hibernate.connection.username = \ ericy hibernate.connection.password = \ synnex2k2 hibernate.transaction.factory_class = \ org.hibernate.transaction.JDBCTransactionFacto ry hibernate.connection.url = \ jdbc:sybase:Tds:192.168.200.11:4500/CIS hibernate.connection.driver_class = \ com.sybase.jdbc2.jdbc.SybDriver hibernate.connection.username = \ ericy hibernate.connection.password = \ synnex2k2 hibernate.transaction.factory_class = \ org.hibernate.transaction.JDBCTransactionFacto ry

10 BeanSoft | 10 Configuration How to get SessionFactory For properties file (hibernate.properties) For XML file (hibernate.cfg.xml) Configuration cfg = new Configuration().addResource(“Customer.hbm.xml").addResource(“Address.hbm.xml"); // If not use the default configure file // cfg.setProperties( ); SessionFactory sessionFactory = cfg.buildSessionFactory(); Configuration cfg = new Configuration().addResource(“Customer.hbm.xml").addResource(“Address.hbm.xml"); // If not use the default configure file // cfg.setProperties( ); SessionFactory sessionFactory = cfg.buildSessionFactory(); SessionFactory sf = new Configuration().configure().buildSessionFactory(); // If not use the default configure file SessionFactory sf = new Configuration().configure(“cisdb.cfg.xml”).buildSessionFactory(); SessionFactory sf = new Configuration().configure().buildSessionFactory(); // If not use the default configure file SessionFactory sf = new Configuration().configure(“cisdb.cfg.xml”).buildSessionFactory();

11 BeanSoft | 11 Persistent classes Example

12 BeanSoft | 12 Persistent classes Persistent class Declare accessors and mutators for persistent fields Implement a no-argument constructor Provide an identifier property Prefer non-final classes Collection property is an interface Class sample public class AuctionItem { private Long _id; private Set _bids; private Bid _successfulBid private String _description; public AuctionItem () {}; public Long getId() { return _id; } private void setId(Long id) { _id = id; } public String getDescription() { return _description; } public void setDescription(String desc){ _description=desc; } … }

13 BeanSoft | 13 Persistent classes XML Mapping Readable metadata Column/table mappings Surrogate key generation strategy Collection metadata Fetching strategies XML Sample <class name=“AuctionItem” table=“AUCTION_ITEM”> <many-to-one name=“successfulBid” column=“SUCCESSFUL_BID_ID” class=“Bid” /> <set name=“bids” cascade=“all” lazy=“true”>

14 BeanSoft | 14 Persistent classes Code sample AuctionItem item = new AuctionItem(); item.setItemName(“XXX”); … Session session = null; Transaction tx = null; try { session = sessionFactory.openSession(); tx = session.beginTransaction(); // do your work session.save(item); tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); throw e; } finally { if (session != null) session.close(); }

15 BeanSoft | 15 Basic O/R mapping class <class name="ClassName" (1) table="tableName" (2) discriminator-value="discriminator_value" (3) mutable="true|false" (4) schema="owner" (5) catalog="catalog“(6) dynamic-update="true|false" (8) dynamic-insert="true|false" (9) select-before-update="true|false" (10) where="arbitrary sql where condition" (12) batch-size="N" (14) optimistic-lock="none|version|dirty|all" (15) lazy="true|false" (16) /> (1)name: The fully qualified Java class name of the persistent class (or interface). (2)table (optional - defaults to the unqualified class name): The name of its database table. (15)optimistic-lock (optional, defaults to version): Determines the optimistic locking strategy.

16 BeanSoft | 16 Basic O/R mapping id <id name="propertyName" (1) type="typename" (2) column="column_name" (3) unsaved-value="null|any|none|undefined|id_value" (4) access="field|property|ClassName"> (5) (6) (1) name: The name of the identifier property. (2) type: A name that indicates the Hibernate type. (3) column (optional - defaults to the property name): The name of the primary key column. (4) unsaved-value (optional): An identifier property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session. (6) The built-in generator: assigned, hilo, seqhilo, increment, identity, sequence, native, uuid (hibernate 3.0), foreign, select (hibernate 3.0)

17 BeanSoft | 17 Basic O/R mapping composite-id <composite-id name="propertyName" class="ClassName" unsaved-value="undefined|any|none" access="field|property|ClassName">...... For Example : (1) (2)

18 BeanSoft | 18 Basic O/R mapping version <version column="version_column“(1) name="propertyName" (2) type="typename" (3) access="field|property|ClassName“(4) unsaved-value="null|negative|undefined" (5) /> (1) column (optional - defaults to the property name): The name of the column holding the version number. (2) name: The name of a property of the persistent class. (3) type (optional - defaults to integer): The type of the version number. Version numbers may be of Hibernate type long, integer, short, timestamp or calendar. (4) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value. (5) unsaved-value (optional - defaults to undefined): A version property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session. (undefined specifies that the identifier property value should be used.) Declaring a nullable version or timestamp property is an easy way to avoid any problems with transitive reattachment in Hibernate, especially useful for people using assigned identifiers or composite keys!

19 BeanSoft | 19 Basic O/R mapping property <property name="propertyName" (1) column="column_name" (2) type="typename" (3) update="true|false" (4) insert="true|false" (4) formula="arbitrary SQL expression" (5) lazy="true|false" (7) unique="true|false" (8) not-null="true|false" (9) optimistic-lock="true|false" (10) /> (4) update, insert (optional - defaults to true) : specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. (5) formula (optional): an SQL expression that defines the value for a computed property. (7) lazy (optional - defaults to false): Specifies that this property should be fetched lazily when the instance variable is first accessed. (8) unique (optional): Enable the DDL generation of a unique constraint for the columns. (9) not-null (optional): Enable the DDL generation of a nullability constraint for the columns. (10) optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, determines if a version increment should occur when this property is dirty.

20 BeanSoft | 20 Collection (,,,, ) Example - set Collection mapping elementclass public class Product { private String serialNumber; private Set images = new HashSet(); } =========================== <id name="serialNumber" column="productSerialNumber"/> <set name="images" table="ITEM_IMAGE"> <element type="string“ column="FILENAME" /> public class Product { private String serialNumber; private Set parts = new HashSet(); } ========================== <id name="serialNumber" column="productSerialNumber"/> <key column="productSerialNumber“/>

21 BeanSoft | 21 Collection mapping Example - listExample - map public class Customer { private String customerNo; private List addresses = new ArrayList(); … … } ===================== … … public class Customer { private String customerNo; private Map addresses = new HashMap(); … … } ===================== … <index column="addr_no“ type=“integer”/> …

22 BeanSoft | 22 Association mapping many-to-one <many-to-one name="propertyName" (1) column="column_name" (2) class="ClassName" (3) cascade="cascade_style" (4) fetch="join|select" (5) update="true|false" (6) insert="true|false" (6) property-ref="propertyNameFromAssociatedClass" (7) access="field|property|ClassName" (8) unique="true|false" (9) not-null="true|false" (10) optimistic-lock="true|false" (11) lazy="true|false" (12) /> (1)name: The name of the property (2)column (optional): The name of the foreign key column. This may also be specified by nested element(s). (3)class (optional): The name of the associated class. (4)cascade (optional): Specifies which operations should be cascaded from the parent object to the associated object. (5)fetch (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.

23 BeanSoft | 23 Association mapping many to one (example) <many-to-one name="address" column="addressId" not-null="true“ class=“Address”/> create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key ) create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key )

24 BeanSoft | 24 Association mapping one to one (example) A one-to-one association on a foreign key <many-to-one name="address“ column="addressId“ unique="true“ not-null="true"/> create table Person ( personId bigint not null primary key, addressId bigint not null unique) create table Address ( addressId bigint not null primary key ) create table Person ( personId bigint not null primary key, addressId bigint not null unique) create table Address ( addressId bigint not null primary key )

25 BeanSoft | 25 Association mapping one to one (example) A one-to-one association on a primary key person create table Person ( personId bigint not null primary key ) create table Address ( personId bigint not null primary key ) create table Person ( personId bigint not null primary key ) create table Address ( personId bigint not null primary key )

26 BeanSoft | 26 Association mapping one to many (example) A one-to-many association on a foreign key create table Person ( personId bigint not null primary key ) create table Address ( addressId bigint not null primary key, personId bigint not null ) create table Person ( personId bigint not null primary key ) create table Address ( addressId bigint not null primary key, personId bigint not null )

27 BeanSoft | 27 Association mapping one to many (example) A one-to-many association on a join table create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId not null, addressId bigint not null) create table Address ( addressId bigint not null primary key ) create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId not null, addressId bigint not null) create table Address ( addressId bigint not null primary key )

28 BeanSoft | 28 Association mapping many to many (example) A many-to-many association on a join table create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId not null, addressId bigint not null) create table Address ( addressId bigint not null primary key ) create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId not null, addressId bigint not null) create table Address ( addressId bigint not null primary key )

29 BeanSoft | 29 Component mapping dependent objects create table Person ( personId bigint not null primary key,name varchar not null, street varchar null, zipcode varchar null, city varchar null, state varchar null, country varchar null ) create table Person ( personId bigint not null primary key,name varchar not null, street varchar null, zipcode varchar null, city varchar null, state varchar null, country varchar null )

30 BeanSoft | 30 Inheritance mapping table per class-hierarchy Suppose we have an interface Payment, with implementors CreditCardPayment, CashPayment, ChequePayment. The table per class-hierarchy mapping would look like:............

31 BeanSoft | 31 Inheritance mapping table per subclass Four tables are required. The three subclass tables have primary key associations to the superclass table.............

32 BeanSoft | 32 Inheritance mapping table per subclass, using a discriminator............

33 BeanSoft | 33 Inheritance mapping table per concrete class Three tables are involved – no table for the interface (super class).............


Download ppt "Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces."

Similar presentations


Ads by Google