SlideShare a Scribd company logo
Hibernate www.intellibitz.com   [email_address]
Introduction What is Persistence? Storing data in a RDBMS using SQL (purposely keeping it simple for this discussion) What is Hibernate? Object to Relational Mapping(ORM) tool What is ORM? Transforms data from one representation to another www.intellibitz.com   [email_address]
Introduction Why ORM? Productivity (reduce development time) Maintainability (minimize effects between the object and the relational model when changes) Performance (major bottlenecks are removed for a wide variety of database) Vendor independence (much easier to develop a cross-platform application) www.intellibitz.com   [email_address]
Architecture www.intellibitz.com   [email_address]
Architecture www.intellibitz.com   [email_address]
Important definitions SessionFactory A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level. www.intellibitz.com   [email_address]
Important definitions Session A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier. www.intellibitz.com   [email_address]
Important definitions Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer. www.intellibitz.com   [email_address]
Important definitions Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session. www.intellibitz.com   [email_address]
Important definitions Transaction (Optional) 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. However, transaction demarcation, either using the underlying API or Transaction, is never optional! www.intellibitz.com   [email_address]
Important definitions 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.l! www.intellibitz.com   [email_address]
Important definitions TransactionFactory (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer. www.intellibitz.com   [email_address]
Instance States Transient The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value). www.intellibitz.com   [email_address]
Instance States Persistent The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object).  www.intellibitz.com   [email_address]
Instance States Detached The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corrsponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.  www.intellibitz.com   [email_address]
Configuration Programmatic configuration An instance of org.hibernate.cfg.Configuration  represents an entire set of mappings of an application's Java types to an SQL database. The Configuration is used to build an (immutable) SessionFactory. The mappings are compiled from various XML mapping files. www.intellibitz.com   [email_address]
Configuration obtain a Configuration instance by instantiating it directly and specifying XML mapping documents Configuration cfg = new Configuration() .addResource("Item.hbm.xml") .addResource("Bid.hbm.xml"); www.intellibitz.com   [email_address]
Configuration An alternative (sometimes better) way is to specify the mapped class, and let Hibernate find the mapping document for you Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class); www.intellibitz.com   [email_address]
Configuration A Configuration also allows you to specify configuration properties: Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect") .setProperty("hibernate.order_updates", "true"); www.intellibitz.com   [email_address]
Configuration Many ways to pass configuration properties: Pass an instance of java.util.Properties to Configuration.setProperties(). Place hibernate.properties in classpath. Set System properties using java -Dprop=val. Include <property> elements in hibernate.cfg.xml  hibernate.properties is the easiest approach. Configuration is a startup-time object, to be discarded once a SessionFactory is created.  www.intellibitz.com   [email_address]
Configuration Obtaining a SessionFactory After parsing all mappings by the Configuration, the application must obtain a factory for Session instances. This factory is intended to be shared by all application threads. SessionFactory sessions = cfg.buildSessionFactory(); your application can instantiate more than one SessionFactory. This is useful if you are using more than one database.  www.intellibitz.com   [email_address]
Configuration JDBC connections Session session = sessions.openSession(); Hibernate will obtain (and pool) connections using java.sql.DriverManager if you set the following properties: www.intellibitz.com   [email_address]
Configuration hibernate.connection.driver_class  jdbc driver class hibernate.connection.url jdbc URL hibernate.connection.username database user hibernate.connection.password database user password hibernate.connection.pool_size maximum number of pooled connections www.intellibitz.com   [email_address]
Connection Pool To use a third party pool for best performance and stability Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use C3P0. www.intellibitz.com   [email_address]
Connection Pool C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib directory. Hibernate will use its C3P0ConnectionProvider for connection pooling if you set hibernate.c3p0.* properties.  www.intellibitz.com   [email_address]
Connection Pool Here is an example hibernate.properties file for C3P0: hibernate.connection.driver_class = org.postgresql.Driver hibernate.connection.url = jdbc:postgresql://localhost/mydatabase hibernate.connection.username = myuser hibernate.connection.password = secret hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statements=50 hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect www.intellibitz.com   [email_address]
Datasource For use inside an application server, configure Hibernate to obtain connections from an application server Datasource registered in JNDI. You'll need to set at least one of the following properties: hibernate.connection.datasource datasource JNDI name hibernate.jndi.url URL of the JNDI provider (optional) hibernate.jndi.class class of the JNDI InitialContextFactory (optional) hibernate.connection.username database user (optional) hibernate.connection.password database user password (optional) www.intellibitz.com   [email_address]
Datasource hibernate.properties file for an application server provided JNDI datasource: hibernate.connection.datasource = java:/comp/env/jdbc/test hibernate.transaction.factory_class =  org.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class =  org.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect www.intellibitz.com   [email_address]
SQL Dialects always set the hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database. If you specify a dialect, Hibernate will use sensible defaults for some of the other properties listed above, saving you the effort of specifying them manually. www.intellibitz.com   [email_address]
XML configuration file An alternative approach to configuration is to specify a full configuration in a file named hibernate.cfg.xml. This file can be used as a replacement for the hibernate.properties file or, if both are present, to override properties. The XML configuration file is by default expected to be in the root of your CLASSPATH. www.intellibitz.com   [email_address]
XML configuration file <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;> <hibernate-configuration> <!-- a SessionFactory instance listed as /jndi/name --> <session-factory name=&quot;java:hibernate/SessionFactory&quot;> <!-- properties --> <property name=&quot;connection.datasource&quot;>java:/comp/env/jdbc/MyDB</property> <property name=&quot;dialect&quot;>org.hibernate.dialect.MySQLDialect</property> <property name=&quot;show_sql&quot;>false</property> <property name=&quot;transaction.factory_class&quot;> org.hibernate.transaction.JTATransactionFactory </property> <property name=&quot;jta.UserTransaction&quot;>java:comp/UserTransaction</property> <!-- mapping files --> <mapping resource=&quot;org/hibernate/auction/Item.hbm.xml&quot;/> <mapping resource=&quot;org/hibernate/auction/Bid.hbm.xml&quot;/> <!-- cache settings --> <class-cache class=&quot;org.hibernate.auction.Item&quot; usage=&quot;read-write&quot;/> <class-cache class=&quot;org.hibernate.auction.Bid&quot; usage=&quot;read-only&quot;/> <collection-cache collection=&quot;org.hibernate.auction.Item.bids&quot; usage=&quot;read-write&quot;/> </session-factory> </hibernate-configuration> www.intellibitz.com   [email_address]
XML configuration file With the XML configuration, starting Hibernate is then as simple as SessionFactory sf = new Configuration().configure().buildSessionFactory() pick a different XML configuration file using SessionFactory sf = new Configuration() .configure(&quot;catdb.cfg.xml&quot;) .buildSessionFactory(); www.intellibitz.com   [email_address]
Persistent Classes Persistent classes are classes that implement the entities of the business problem. Not all instances of a persistent class are considered to be in the persistent state - an instance may instead be transient or detached. Hibernate works best if these classes follow the Plain Old Java Object (POJO) model.  www.intellibitz.com   [email_address]
Persistent Classes 4 simple rules to follow Implement a no-argument constructor Provide an identifier property (optional)  Prefer non-final classes (optional) Declare accessors and mutators for persistent fields (optional) www.intellibitz.com   [email_address]
Persistent Classes Implementing equals() and hashCode() intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations) and intend to use reattachment of detached instances  www.intellibitz.com   [email_address]
Persistent Classes Business key equality recommend implementing equals() and hashCode()  using Business key equality. Business key equality means that the equals() method compares only the properties that form the business key, a key that would identify our instance in the real world (a natural candidate key) www.intellibitz.com   [email_address]
Persistent Classes Business key equality public class Cat { ... public boolean equals(Object other) { if (this == other) return true; if ( !(other instanceof Cat) ) return false; final Cat cat = (Cat) other; if ( !cat.getLitterId().equals( getLitterId() ) ) return false; if ( !cat.getMother().equals( getMother() ) ) return false; return true; } public int hashCode() { int result; result = getMother().hashCode(); result = 29 * result + getLitterId(); return result; } } www.intellibitz.com   [email_address]
Basic O/R Mapping Mapping declaration O/R mappings are defined in an XML document.  designed to be readable and hand-editable.  Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations. many users write the XML by hand, but a number of tools exist to generate the mapping, including XDoclet, Middlegen and AndroMDA. www.intellibitz.com   [email_address]
Basic O/R Mapping <?xml version=&quot;1.0&quot;?> <!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;> <hibernate-mapping package=&quot;eg&quot;> <class name=&quot;Cat&quot; table=&quot;cats&quot; discriminator-value=&quot;C&quot;> <id name=&quot;id&quot;> <generator class=&quot;native&quot;/> </id> <discriminator column=&quot;subclass&quot; type=&quot;character&quot;/> <property name=&quot;weight&quot;/> <property name=&quot;birthdate&quot; type=&quot;date&quot; not-null=&quot;true&quot; update=&quot;false&quot;/> <property name=&quot;color&quot; type=&quot;eg.types.ColorUserType&quot; not-null=&quot;true&quot; update=&quot;false&quot;/> www.intellibitz.com   [email_address] <property name=&quot;sex&quot; not-null=&quot;true&quot; update=&quot;false&quot;/> <property name=&quot;litterId&quot; column=&quot;litterId&quot; update=&quot;false&quot;/> <many-to-one name=&quot;mother&quot; column=&quot;mother_id&quot; update=&quot;false&quot;/> <set name=&quot;kittens&quot; inverse=&quot;true&quot; order-by=&quot;litter_id&quot;> <key column=&quot;mother_id&quot;/> <one-to-many class=&quot;Cat&quot;/> </set> <subclass name=&quot;DomesticCat&quot; discriminator-value=&quot;D&quot;> <property name=&quot;name&quot; type=&quot;string&quot;/> </subclass> </class> <class name=&quot;Dog&quot;> <!-- mapping for Dog could go here --> </class> </hibernate-mapping>
Basic O/R Mapping class <class name=&quot;ClassName&quot;  (1) table=&quot;tableName&quot;  (2) discriminator-value=&quot;discriminator_value&quot;  (3) mutable=&quot;true|false&quot;  (4) schema=&quot;owner&quot;  (5) catalog=&quot;catalog&quot;  (6) proxy=&quot;ProxyInterface&quot;  (7) dynamic-update=&quot;true|false&quot;  (8) dynamic-insert=&quot;true|false&quot;  (9) select-before-update=&quot;true|false&quot;  (10) polymorphism=&quot;implicit|explicit&quot;  (11) where=&quot;arbitrary sql where condition&quot;  (12) persister=&quot;PersisterClass&quot;  (13) batch-size=&quot;N&quot;  (14) optimistic-lock=&quot;none|version|dirty|all&quot;  (15) lazy=&quot;true|false&quot;  (16) entity-name=&quot;EntityName&quot;  (17) check=&quot;arbitrary sql check condition&quot;  (18) rowid=&quot;rowid&quot;  (19) subselect=&quot;SQL expression&quot;  (20) abstract=&quot;true|false&quot;  (21) node=&quot;element-name&quot; /> www.intellibitz.com   [email_address]
Basic O/R Mapping id <id name=&quot;propertyName&quot;  (1) type=&quot;typename&quot;  (2) column=&quot;column_name&quot;  (3) unsaved-value=&quot;null|any|none|undefined|id_value&quot;  (4) access=&quot;field|property|ClassName&quot;>  (5) node=&quot;element-name|@attribute-name|element/@attribute|.&quot; <generator class=&quot;generatorClass&quot;/> </id> generator <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;cat_id&quot;> <generator class=&quot;org.hibernate.id.TableHiLoGenerator&quot;> <param name=&quot;table&quot;>uid_table</param> <param name=&quot;column&quot;>next_hi_value_column</param> </generator> </id> www.intellibitz.com   [email_address]
Basic O/R Mapping property <property name=&quot;propertyName&quot;  (1) column=&quot;column_name&quot;  (2) type=&quot;typename&quot;  (3) update=&quot;true|false&quot;  (4) insert=&quot;true|false&quot;  (4) formula=&quot;arbitrary SQL expression&quot;  (5) access=&quot;field|property|ClassName&quot;  (6) lazy=&quot;true|false&quot;  (7) unique=&quot;true|false&quot;  (8) not-null=&quot;true|false&quot;  (9) optimistic-lock=&quot;true|false&quot;  (10) generated=&quot;never|insert|always&quot;  (11) node=&quot;element-name|@attribute-name|element/@attribute|.&quot; index=&quot;index_name&quot; unique_key=&quot;unique_key_id&quot; length=&quot;L&quot; precision=&quot;P&quot; scale=&quot;S&quot; /> www.intellibitz.com   [email_address]
Basic O/R Mapping many-to-one An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a many-to-one association: a foreign key in one table is referencing the primary key column(s) of the target table. <many-to-one name=&quot;product&quot; class=&quot;Product&quot; column=&quot;PRODUCT_ID&quot;/> www.intellibitz.com   [email_address]
Basic O/R Mapping one-to-one There are two varieties of one-to-one association: primary key associations unique foreign key associations  www.intellibitz.com   [email_address]
Basic O/R Mapping one-to-one Primary key associations don't need an extra table column; if two rows are related by the association then the two table rows share the same primary key value. So if you want two objects to be related by a primary key association, you must make sure that they are assigned the same identifier value!  www.intellibitz.com   [email_address]
Basic O/R Mapping one-to-one <class name=&quot;person&quot; table=&quot;PERSON&quot;> <id name=&quot;id&quot; column=&quot;PERSON_ID&quot;> <generator class=&quot;foreign&quot;> <param name=&quot;property&quot;>employee</param> </generator> </id> ... <one-to-one name=&quot;employee&quot; class=&quot;Employee&quot; constrained=&quot;true&quot;/> </class> www.intellibitz.com   [email_address]
Hibernate Types Entities and Values An entity exists independently of any other objects holding references to the entity. Contrast this with the usual Java model where an unreferenced object is garbage collected. Entities must be explicitly saved and deleted (except that saves and deletions may be cascaded  from a parent entity to its children). Entities support circular and shared references. They may also be versioned. www.intellibitz.com   [email_address]
Hibernate Types Entities and Values Values are primitives, collections (not what's inside a collection), components and certain immutable objects. Unlike entities, values (in particular collections and components) are persisted and deleted by reachability. Since value objects (and primitives) are persisted and deleted along with their containing entity they may not be independently versioned. Values have no independent identity, so they cannot be shared by two entities or collections. www.intellibitz.com   [email_address]
Hibernate Types Entities and Values Entities are mapped by <class>, <subclass> and so on. For value types we use <property>, <component>, etc, usually with a type  attribute. www.intellibitz.com   [email_address]
Jdk 5 Annotations @Entity(access = AccessType.FIELD) public class Customer implements Serializable { @Id; Long id; String firstName; String lastName; Date birthday; @Transient Integer age; @Embedded private Address homeAddress; @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name=&quot;CUSTOMER_ID&quot;) Set<Order> orders; // Getter/setter and business methods } www.intellibitz.com   [email_address]
Collection Mapping Persistent collections Hibernate requires that persistent collection-valued fields be declared as an interface type. Ex: private Set parts = new HashSet(); When you make the instance persistent - by calling persist(), for example - Hibernate will actually replace the HashSet  with an instance of Hibernate's own implementation of Set. www.intellibitz.com   [email_address]
Collection Mapping Persistent collections Watch out for errors like this: Cat cat = new DomesticCat(); Cat kitten = new DomesticCat(); .... Set kittens = new HashSet(); kittens.add(kitten); cat.setKittens(kittens); session.persist(cat); kittens = cat.getKittens(); // Okay, kittens collection is a Set (HashSet) cat.getKittens(); // Error! Collections instances have the usual behavior of value types. Two entities may not share a reference to the same collection instance. www.intellibitz.com   [email_address]
Collection Mapping <class name=&quot;Product&quot;> <id name=&quot;serialNumber&quot; column=&quot;productSerialNumber&quot;/> <set name=&quot;parts&quot;> <key column=&quot;productSerialNumber&quot; not-null=&quot;true&quot;/> <one-to-many class=&quot;Part&quot;/> </set> </class> <set name=&quot;names&quot; table=&quot;person_names&quot;> <key column=&quot;person_id&quot;/> <element column=&quot;person_name&quot; type=&quot;string&quot;/> </set> <array name=&quot;addresses&quot;  table=&quot;PersonAddress&quot;  cascade=&quot;persist&quot;> <key column=&quot;personId&quot;/> <list-index column=&quot;sortOrder&quot;/> <many-to-many column=&quot;addressId&quot; class=&quot;Address&quot;/> </array> www.intellibitz.com   [email_address]
Collection Mapping Bidirectional associations one-to-many set or bag valued at one end, single-valued at the other  many-to-many set or bag valued at both ends  www.intellibitz.com   [email_address]
Collection Mapping Bidirectional associations many-to-many example <class name=&quot;Category&quot;> <id name=&quot;id&quot; column=&quot;CATEGORY_ID&quot;/> ... <bag name=&quot;items&quot; table=&quot;CATEGORY_ITEM&quot;> <key column=&quot;CATEGORY_ID&quot;/> <many-to-many class=&quot;Item&quot; column=&quot;ITEM_ID&quot;/> </bag> </class> <class name=&quot;Item&quot;> <id name=&quot;id&quot; column=&quot;CATEGORY_ID&quot;/> ... <!-- inverse end --> <bag name=&quot;categories&quot; table=&quot;CATEGORY_ITEM&quot; inverse=&quot;true&quot;> <key column=&quot;ITEM_ID&quot;/> <many-to-many class=&quot;Category&quot; column=&quot;CATEGORY_ID&quot;/> </bag> </class> www.intellibitz.com   [email_address]
Collection Mapping Bidirectional associations Changes made only to the inverse end of the association are not  persisted. This means that Hibernate has two representations in memory for every bidirectional association, one link from A to B and another link from B to A.  category.getItems().add(item);  // The category now &quot;knows&quot; about the relationship item.getCategories().add(category);  // The item now &quot;knows&quot; about the relationship session.persist(item);  // The relationship won't be saved! session.persist(category);  // The relationship will be saved The non-inverse side is used to save the in-memory representation to the database.  www.intellibitz.com   [email_address]
Association Mappings Unidirectional associations many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot;  column=&quot;addressId&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Association Mappings Unidirectional associations one to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot;  column=&quot;addressId&quot;  unique=&quot;true&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key, addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Association Mappings Unidirectional associations with join tables one to many <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot; table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; unique=&quot;true&quot; class=&quot;Address&quot;/> </set> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId not null, addressId bigint not null primary key ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Association Mappings Unidirectional associations with join tables many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot;  optional=&quot;true&quot;> <key column=&quot;personId&quot; unique=&quot;true&quot;/> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot;  not-null=&quot;true&quot;/> </join> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Association Mappings Unidirectional associations with join tables many to many <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot; table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; class=&quot;Address&quot;/> </set> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Association Mappings Bidirectional associations one to many / many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot;  column=&quot;addressId&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;people&quot; inverse=&quot;true&quot;> <key column=&quot;addressId&quot;/> <one-to-many class=&quot;Person&quot;/> </set> </class> create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Association Mappings Bidirectional associations one to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot;  column=&quot;addressId&quot;  unique=&quot;true&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <one-to-one name=&quot;person&quot;  property-ref=&quot;address&quot;/> </class> create table Person ( personId bigint not null primary key, addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Association Mappings Bidirectional associations with join tables one to many / many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot;  table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; unique=&quot;true&quot; class=&quot;Address&quot;/> </set> </class> www.intellibitz.com   [email_address] <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot;  inverse=&quot;true&quot;  optional=&quot;true&quot;> <key column=&quot;addressId&quot;/> <many-to-one name=&quot;person&quot; column=&quot;personId&quot; not-null=&quot;true&quot;/> </join> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null, addressId bigint not null primary key ) create table Address ( addressId bigint not null primary key )
Association Mappings Bidirectional associations with join tables one to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot;  optional=&quot;true&quot;> <key column=&quot;personId&quot;  unique=&quot;true&quot;/> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot;  not-null=&quot;true&quot; unique=&quot;true&quot;/> </join> </class> www.intellibitz.com   [email_address] <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot;  optional=&quot;true&quot; inverse=&quot;true&quot;> <key column=&quot;addressId&quot;  unique=&quot;true&quot;/> <many-to-one name=&quot;person&quot; column=&quot;personId&quot;  not-null=&quot;true&quot; unique=&quot;true&quot;/> </join> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null primary key, addressId bigint not null unique ) create table Address ( addressId bigint not null primary key )
Association Mappings Bidirectional associations with join tables many to many <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot; table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; class=&quot;Address&quot;/> </set> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;people&quot; inverse=&quot;true&quot; table=&quot;PersonAddress&quot;> <key column=&quot;addressId&quot;/> <many-to-many column=&quot;personId&quot; class=&quot;Person&quot;/> </set> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com   [email_address]
Component Mapping Dependent Objects A component is a contained object that is persisted as a value type, not an entity reference. The term &quot;component&quot; refers to the object-oriented notion of composition (not to architecture-level components). www.intellibitz.com   [email_address]
Component Mapping public class Person { private java.util.Date birthday; private Name name; private String key; public String getKey() { return key; } private void setKey(String key) { this.key=key; } public java.util.Date getBirthday() { return birthday; } public void setBirthday(java.util.Date birthday) { this.birthday = birthday; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } ...... ...... } www.intellibitz.com   [email_address] public class Name { char initial; String first; String last; public String getFirst() { return first; } void setFirst(String first) { this.first = first; } public String getLast() { return last; } void setLast(String last) { this.last = last; } public char getInitial() { return initial; } void setInitial(char initial) { this.initial = initial; } }
Component Mapping Hibernate mapping: <class name=&quot;eg.Person&quot; table=&quot;person&quot;> <id name=&quot;Key&quot; column=&quot;pid&quot; type=&quot;string&quot;> <generator class=&quot;uuid&quot;/> </id> <property name=&quot;birthday&quot; type=&quot;date&quot;/> <component name=&quot;Name&quot; class=&quot;eg.Name&quot;> <!-- class attribute optional --> <property name=&quot;initial&quot;/> <property name=&quot;first&quot;/> <property name=&quot;last&quot;/> </component> </class> The person table would have the columns pid, birthday, initial, first and last. www.intellibitz.com   [email_address]
Component Mapping Collections of dependent objects Collections of components are supported (eg. an array of type Name). Declare your component collection by replacing the <element> tag with a <composite-element> tag. <set name=&quot;someNames&quot; table=&quot;some_names&quot; lazy=&quot;true&quot;> <key column=&quot;id&quot;/> <composite-element class=&quot;eg.Name&quot;> <!-- class attribute required --> <property name=&quot;initial&quot;/> <property name=&quot;first&quot;/> <property name=&quot;last&quot;/> </composite-element> </set> www.intellibitz.com   [email_address]
Inheritance Mapping The Three Strategies * table per class hierarchy table per subclass table per concrete class  supports a fourth, slightly different kind of polymorphism: implicit polymorphism www.intellibitz.com   [email_address]
Inheritance Mapping Table per class hierarchy Exactly one table is required. one big limitation of this mapping strategy: columns declared by the subclasses, such as CCTYPE, may not have NOT NULL constraints. www.intellibitz.com   [email_address] <class name=&quot;Payment&quot; table=&quot;PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <discriminator column=&quot;PAYMENT_TYPE&quot; type=&quot;string&quot;/> <property name=&quot;amount&quot; column=&quot;AMOUNT&quot;/> ... <subclass name=&quot;CreditCardPayment&quot; discriminator-value=&quot;CREDIT&quot;> <property name=&quot;creditCardType&quot; column=&quot;CCTYPE&quot;/> ... </subclass> <subclass name=&quot;CashPayment&quot; discriminator-value=&quot;CASH&quot;> ... </subclass> <subclass name=&quot;ChequePayment&quot; discriminator-value=&quot;CHEQUE&quot;> ... </subclass> </class>
Inheritance Mapping Table per subclass  Four tables are required. The three subclass tables have primary key associations to the superclass table (so the relational model is actually a one-to-one association). www.intellibitz.com   [email_address] <class name=&quot;Payment&quot; table=&quot;PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;AMOUNT&quot;/> ... <joined-subclass name=&quot;CreditCardPayment&quot; table=&quot;CREDIT_PAYMENT&quot;> <key column=&quot;PAYMENT_ID&quot;/> <property name=&quot;creditCardType&quot; column=&quot;CCTYPE&quot;/> ... </joined-subclass> <joined-subclass name=&quot;CashPayment&quot; table=&quot;CASH_PAYMENT&quot;> <key column=&quot;PAYMENT_ID&quot;/> ... </joined-subclass> <joined-subclass name=&quot;ChequePayment&quot; table=&quot;CHEQUE_PAYMENT&quot;> <key column=&quot;PAYMENT_ID&quot;/> ... </joined-subclass> </class>
Inheritance Mapping Table per concrete class  Three tables are involved for the subclasses. Each table defines columns for all properties of the class, including inherited properties. The limitation of this approach is that if a property is mapped on the superclass, the column name must be the same on all subclass tables. If your superclass is abstract, map it with abstract=&quot;true&quot;. Of course, if it is not abstract, an additional table (defaults to PAYMENT in the example above) is needed to hold instances of the superclass.  www.intellibitz.com   [email_address] <class name=&quot;Payment&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;PAYMENT_ID&quot;> <generator class=&quot;sequence&quot;/> </id> <property name=&quot;amount&quot; column=&quot;AMOUNT&quot;/> ... <union-subclass name=&quot;CreditCardPayment&quot; table=&quot;CREDIT_PAYMENT&quot;> <property name=&quot;creditCardType&quot; column=&quot;CCTYPE&quot;/> ... </union-subclass> <union-subclass name=&quot;CashPayment&quot; table=&quot;CASH_PAYMENT&quot;> ... </union-subclass> <union-subclass name=&quot;ChequePayment&quot; table=&quot;CHEQUE_PAYMENT&quot;> ... </union-subclass> </class>
Inheritance Mapping Table per concrete class using implicit polymorphism Notice that nowhere do we mention the Payment interface explicitly. Also notice that properties of Payment are mapped in each of the subclasses. If you want to avoid duplication, consider using XML entities  The disadvantage of this approach is that Hibernate does not generate SQL UNIONs when performing polymorphic queries. For this mapping strategy, a polymorphic association to Payment is usually mapped using <any>.  www.intellibitz.com   [email_address] <class name=&quot;CreditCardPayment&quot; table=&quot;CREDIT_PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;CREDIT_PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;CREDIT_AMOUNT&quot;/> ... </class> <class name=&quot;CashPayment&quot; table=&quot;CASH_PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;CASH_PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;CASH_AMOUNT&quot;/> ... </class> <class name=&quot;ChequePayment&quot; table=&quot;CHEQUE_PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;CHEQUE_PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;CHEQUE_AMOUNT&quot;/> ... </class>
Working with Objects Hibernate Object states Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Use the Hibernate Session to make an object persistent (and let Hibernate take care SQL statements to be executed for this transition). www.intellibitz.com   [email_address]
Working with Objects Hibernate Object states Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes.  www.intellibitz.com   [email_address]
Working with Objects Hibernate Object states Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. www.intellibitz.com   [email_address]
Working with Objects Making Objects Persistent a transient instance becomes persistent by associating it with a session: DomesticCat fritz = new DomesticCat(); fritz.setColor(Color.GINGER); fritz.setSex('M'); fritz.setName(&quot;Fritz&quot;); Long generatedId = (Long) sess.save(fritz); If Cat has a generated identifier, the identifier is generated and assigned to the cat when save() is called. If Cat has an assigned  identifier, or a composite key, the identifier should be assigned to the cat instance before calling save().  www.intellibitz.com   [email_address]
Working with Objects Loading an Object use load() to retrieve a persistent instance by its identifier. load() takes a class object and will load the state into a newly instantiated instance of that class, in persistent state. Cat fritz = (Cat) sess.load(Cat.class, generatedId); If not certain that a matching row exists, use get(), which hits the database immediately and returns null if there is no matching row. www.intellibitz.com   [email_address]
Working with Objects Querying Hibernate supports an easy-to-use but powerful object oriented query language (HQL). For programmatic query creation, Hibernate supports a sophisticated Criteria and Example query feature (QBC and QBE). You may also express your query in the native SQL of your database, with optional support from Hibernate for result set conversion into objects. www.intellibitz.com   [email_address]
Working with Objects Executing Queries HQL and native SQL queries are represented with an instance of org.hibernate.Query. This interface offers methods for parameter binding, result set handling, and for the execution of the actual query. You always obtain a Query using the current Session: List mothers = session.createQuery( &quot;select mother from Cat as cat join cat.mother as mother where cat.name = ?&quot;) .setString(0, name) .list(); www.intellibitz.com   [email_address]
Working with Objects Executing Queries A query is usually executed by invoking list(), the result loaded completely into a collection in memory. Entity instances retrieved by a query are in persistent state. The uniqueResult() method offers a shortcut if you know your query will only return a single object.  www.intellibitz.com   [email_address]
Working with Objects Iterating results Occasionally, executing the query using the iterate() method is faster. This will only usually be the case if you expect that the actual entity instances returned by the query will already be in the session or second-level cache. If they are not already cached, iterate() will be slower than list()  and might require many database hits for a simple query. www.intellibitz.com   [email_address]
Working with Objects Queries that return tuples Hibernate queries sometimes return tuples of objects, in which case each tuple is returned as an array: Iterator kittensAndMothers = sess.createQuery( &quot;select kitten, mother from Cat kitten join kitten.mother mother&quot;) .list() .iterator(); while ( kittensAndMothers.hasNext() ) { Object[] tuple = (Object[]) kittensAndMothers.next(); Cat kitten  = tuple[0]; Cat mother  = tuple[1]; .... } www.intellibitz.com   [email_address]
Working with Objects Scalar results Queries may specify a property of a class in the select clause. They may even call SQL aggregate functions. Properties or aggregates are considered &quot;scalar&quot; results. Iterator results = sess.createQuery( &quot;select cat.color, min(cat.birthdate), count(cat) from Cat cat &quot; + &quot;group by cat.color&quot;) .list() .iterator(); while ( results.hasNext() ) { Object[] row = (Object[]) results.next(); Color type = (Color) row[0]; Date oldest = (Date) row[1]; Integer count = (Integer) row[2]; ..... } www.intellibitz.com   [email_address]
Working with Objects Bind Parameters Contrary to JDBC, Hibernate numbers parameters from zero.  Named parameters are identifiers of the form :name in the query string. The advantages of named parameters are: named parameters are insensitive to the order they occur in the query string they may occur multiple times in the same query they are self-documenting  www.intellibitz.com   [email_address]
Working with Objects Bind Parameters //named parameter (preferred) Query q = sess.createQuery(&quot;from DomesticCat cat where cat.name = :name&quot;); q.setString(&quot;name&quot;, &quot;Fritz&quot;); Iterator cats = q.iterate(); //positional parameter Query q = sess.createQuery(&quot;from DomesticCat cat where cat.name = ?&quot;); q.setString(0, &quot;Izi&quot;); Iterator cats = q.iterate(); //named parameter list List names = new ArrayList(); names.add(&quot;Izi&quot;); names.add(&quot;Fritz&quot;); Query q = sess.createQuery(&quot;from DomesticCat cat where cat.name in (:namesList)&quot;); q.setParameterList(&quot;namesList&quot;, names); List cats = q.list(); www.intellibitz.com   [email_address]
Working with Objects Pagination If you need to specify bounds upon your result set (the maximum number of rows you want to retrieve and / or the first row you want to retrieve) you should use methods of the Query interface: Query q = sess.createQuery(&quot;from DomesticCat cat&quot;); q.setFirstResult(20); q.setMaxResults(10); List cats = q.list(); Hibernate knows how to translate this limit query into the native SQL of your DBMS.  www.intellibitz.com   [email_address]
Working with Objects Externalizing named queries named queries in the mapping document. <query name=&quot;ByNameAndMaximumWeight&quot;><![CDATA[ from eg.DomesticCat as cat where cat.name = ? and cat.weight > ? ] ]></query> Parameter binding done programatically: Query q = sess.getNamedQuery (&quot;ByNameAndMaximumWeight&quot;); q.setString(0, name); q.setInt(1, minWeight); List cats = q.list(); may also define native SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files. www.intellibitz.com   [email_address]
Working with Objects Externalizing named queries Note that the actual program code is independent of the query language that is used as said above. Also note that a query declaration inside a <hibernate-mapping> element requires a global unique name for the query, while a query declaration inside a <class> element is made unique automatically by prepending the fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.  www.intellibitz.com   [email_address]
Working with Objects Filtering Collections A collection filter may be applied to a persistent collection or array. The query string may refer to this, meaning the current collection element. Collection blackKittens = session.createFilter( pk.getKittens(),  &quot;where this.color = ?&quot;) .setParameter( Color.BLACK, Hibernate.custom(ColorUserType.class) ) .list() ); The returned collection is a copy of the given collection. The original collection is not modified. Observe that filters do not require a from clause (though they may have one if required). www.intellibitz.com   [email_address]
Working with Objects Criteria queries HQL is extremely powerful but some developers prefer to build queries dynamically, using an object-oriented API, rather than building query strings. Hibernate provides an intuitive Criteria query API for these cases: Criteria crit = session.createCriteria(Cat.class); crit.add( Expression.eq( &quot;color&quot;, eg.Color.BLACK ) ); crit.setMaxResults(10); List cats = crit.list(); www.intellibitz.com   [email_address]
Working with Objects Queries in native SQL You may express a query in SQL, using createSQLQuery() and let Hibernate take care of the mapping from result sets to objects. Note that you may at any time call session.connection() and use the JDBC Connection directly. If you chose to use the Hibernate API, you must enclose SQL aliases in braces: List cats = session.createSQLQuery( &quot;SELECT {cat.*} FROM CAT {cat} WHERE ROWNUM<10&quot;,  &quot;cat&quot;,  Cat.class).list(); www.intellibitz.com   [email_address]
Working with Objects Modifying Persistent Objects Transactional persistent instances (ie. objects loaded, saved, created or queried by the Session) may be manipulated by the application and any changes to persistent state will be persisted when the Session  is flushed. So the most straightforward way to update the state of an object is to load() it, and then manipulate it directly, while the Session is open: DomesticCat cat = (DomesticCat) sess.load( Cat.class, new Long(69) ); cat.setName(&quot;PK&quot;); sess.flush();  // changes to cat are automatically detected and persisted www.intellibitz.com   [email_address]
Working with Objects Modifying detached Objects Hibernate supports for reattachment of detached instances using the Session.update() or Session.merge()  methods: // in the first session Cat cat = (Cat) firstSession.load(Cat.class, catId); Cat potentialMate = new Cat(); firstSession.save(potentialMate); // in a higher layer of the application cat.setMate(potentialMate); // later, in a new session secondSession.update(cat);  // update cat secondSession.update(mate); // update mate www.intellibitz.com   [email_address]
Working with Objects Modifying detached Objects Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session. In other words, update()  is usually the first method you would call in a fresh session, ensuring that reattachment of your detached instances is the first operation that is executed. www.intellibitz.com   [email_address]
Working with Objects Modifying detached Objects The lock() method also allows an application to reassociate an object with a new session. However, the detached instance has to be unmodified! //just reassociate: sess.lock(fritz, LockMode.NONE); //do a version check, then reassociate: sess.lock(izi, LockMode.READ); //do a version check, using SELECT ... FOR UPDATE, then reassociate: sess.lock(pk, LockMode.UPGRADE); www.intellibitz.com   [email_address]
Working with Objects Automatic State detection The saveOrUpdate() is a general purpose method that either saves a transient instance by generating a new identifier or updates/reattaches the detached instances associated with its current identifier. // in the first session Cat cat = (Cat) firstSession.load(Cat.class, catID); // in a higher tier of the application Cat mate = new Cat(); cat.setMate(mate); // later, in a new session secondSession.saveOrUpdate(cat);  // update existing state (cat has a non-null id) secondSession.saveOrUpdate(mate);  // save the new instance (mate has a null id) www.intellibitz.com   [email_address]
Working with Objects Automatic State detection Usually update() or saveOrUpdate() are used in the following scenario: the application loads an object in the first session the object is passed up to the UI tier some modifications are made to the object the object is passed back down to the business logic tier the application persists these modifications by calling update() in a second session   www.intellibitz.com   [email_address]
Working with Objects Automatic State detection saveOrUpdate() does the following: if the object is already persistent in this session, do nothing if another object associated with the session has the same identifier, throw an exception if the object has no identifier property, save() it if the object's identifier has the value assigned to a newly instantiated object, save() it if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it otherwise update() the object   www.intellibitz.com   [email_address]
Working with Objects Automatic State detection merge() does the following: if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance the persistent instance is returned the given instance does not become associated with the session, it remains detached  www.intellibitz.com   [email_address]
Working with Objects Deleting Persistent Objects Session.delete() will remove an object's state from the database. It's best to think of delete() as making a persistent instance transient. sess.delete(cat); You may delete objects in any order you like, without risk of foreign key constraint violations. It is still possible to violate a NOT NULL constraint on a foreign key column by deleting objects in the wrong order, e.g. if you delete the parent, but forget to delete the children.  www.intellibitz.com   [email_address]
Working with Objects Flushing the Session From time to time the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points before some query executions from org.hibernate.Transaction.commit() from Session.flush()  www.intellibitz.com   [email_address]
Working with Objects Transitive Persistence It is quite cumbersome to save, delete, or reattach individual objects, especially if you deal with a graph of associated objects. A common case is a parent/child relationship. Hibernate does not implement persistence by reachability by default. If you want an operation to be cascaded along an association, you must indicate that in the mapping document using 'cascade'.  www.intellibitz.com   [email_address]

More Related Content

What's hot (20)

Spring (1)
Spring (1)
Aneega
 
Hibernate presentation
Hibernate presentation
Manav Prasad
 
Hibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Introduction to Hibernate
Introduction to Hibernate
Krishnakanth Goud
 
Spring & hibernate
Spring & hibernate
Santosh Kumar Kar
 
24 collections framework interview questions
24 collections framework interview questions
Arun Vasanth
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
Khoa Nguyen
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
Java IO, Serialization
Java IO, Serialization
Hitesh-Java
 
Hibernate Tutorial
Hibernate Tutorial
Ram132
 
Spring - Part 3 - AOP
Spring - Part 3 - AOP
Hitesh-Java
 
Hibernate in Nutshell
Hibernate in Nutshell
Onkar Deshpande
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Hibernate
Hibernate
VISHAL DONGA
 
Hibernate
Hibernate
Ajay K
 
Hibernate Interview Questions
Hibernate Interview Questions
Syed Shahul
 
Dao pattern
Dao pattern
ciriako
 
jpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
Fahad Golra
 
JSP - Part 1
JSP - Part 1
Hitesh-Java
 
Spring (1)
Spring (1)
Aneega
 
Hibernate presentation
Hibernate presentation
Manav Prasad
 
Hibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
24 collections framework interview questions
24 collections framework interview questions
Arun Vasanth
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
Khoa Nguyen
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
Java IO, Serialization
Java IO, Serialization
Hitesh-Java
 
Hibernate Tutorial
Hibernate Tutorial
Ram132
 
Spring - Part 3 - AOP
Spring - Part 3 - AOP
Hitesh-Java
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Hibernate
Hibernate
Ajay K
 
Hibernate Interview Questions
Hibernate Interview Questions
Syed Shahul
 
Dao pattern
Dao pattern
ciriako
 
jpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
Fahad Golra
 

Viewers also liked (20)

Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
Andrus Adamchik
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Brett Meyer
 
Intro To Hibernate
Intro To Hibernate
Amit Himani
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
Brett Meyer
 
UpsilonPiEpsilon-UniversityOfBridgeport-May1997
UpsilonPiEpsilon-UniversityOfBridgeport-May1997
Muthuselvam RS
 
Jsp
Jsp
Mumbai Academisc
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
Ordbms
Ordbms
ramandeep brar
 
Introduction to hibernate
Introduction to hibernate
hr1383
 
Software Quality Assurance
Software Quality Assurance
university of education,Lahore
 
Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19
koolkampus
 
JDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Java Server Pages
Java Server Pages
BG Java EE Course
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Jsp ppt
Jsp ppt
Vikas Jagtap
 
Java Servlets
Java Servlets
Nitin Pai
 
Black box & white-box testing technique
Black box & white-box testing technique
SivaprasanthRentala1975
 
Black & White Box testing
Black & White Box testing
Mohamed Zeinelabdeen Abdelgader Farh jber
 
Software quality assurance
Software quality assurance
Aman Adhikari
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
Andrus Adamchik
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Brett Meyer
 
Intro To Hibernate
Intro To Hibernate
Amit Himani
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
Brett Meyer
 
UpsilonPiEpsilon-UniversityOfBridgeport-May1997
UpsilonPiEpsilon-UniversityOfBridgeport-May1997
Muthuselvam RS
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
Introduction to hibernate
Introduction to hibernate
hr1383
 
Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19
koolkampus
 
JDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Java Servlets
Java Servlets
Nitin Pai
 
Software quality assurance
Software quality assurance
Aman Adhikari
 
Ad

Similar to Hibernate Developer Reference (20)

02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
 
Hibernate
Hibernate
Preetha Ganapathi
 
hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdf
Mytrux1
 
What is hibernate?
What is hibernate?
kanchanmahajan23
 
What is hibernate?
What is hibernate?
kanchanmahajan23
 
Basic Hibernate Final
Basic Hibernate Final
Rafael Coutinho
 
Hibernate presentation
Hibernate presentation
Luis Goldster
 
Hibernate
Hibernate
Murali Pachiyappan
 
Module-3 for career and JFSD ppt for study.pptx
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
What is hibernate?
What is hibernate?
kanchanmahajan23
 
Learn HIBERNATE at ASIT
Learn HIBERNATE at ASIT
ASIT
 
Hibernate Framework
Hibernate Framework
baabtra.com - No. 1 supplier of quality freshers
 
Hibernate introduction
Hibernate introduction
Sagar Verma
 
Patni Hibernate
Patni Hibernate
patinijava
 
inf5750---lecture-2.-c---hibernate-intro.pdf
inf5750---lecture-2.-c---hibernate-intro.pdf
bhqckkgwglxjcuctdf
 
Hibernate for Beginners
Hibernate for Beginners
Ramesh Kumar
 
Hibernate jj
Hibernate jj
Joe Jacob
 
Hibernate
Hibernate
Sujit Kumar
 
Advanced Hibernate
Advanced Hibernate
Haitham Raik
 
hibernate
hibernate
Arjun Shanka
 
Ad

More from Muthuselvam RS (6)

Spring User Guide
Spring User Guide
Muthuselvam RS
 
Gears User Guide
Gears User Guide
Muthuselvam RS
 
Ant User Guide
Ant User Guide
Muthuselvam RS
 
Subversion User Guide
Subversion User Guide
Muthuselvam RS
 
CProgrammingTutorial
CProgrammingTutorial
Muthuselvam RS
 
PHP Web Programming
PHP Web Programming
Muthuselvam RS
 

Recently uploaded (20)

National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 

Hibernate Developer Reference

  • 2. Introduction What is Persistence? Storing data in a RDBMS using SQL (purposely keeping it simple for this discussion) What is Hibernate? Object to Relational Mapping(ORM) tool What is ORM? Transforms data from one representation to another www.intellibitz.com [email_address]
  • 3. Introduction Why ORM? Productivity (reduce development time) Maintainability (minimize effects between the object and the relational model when changes) Performance (major bottlenecks are removed for a wide variety of database) Vendor independence (much easier to develop a cross-platform application) www.intellibitz.com [email_address]
  • 6. Important definitions SessionFactory A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level. www.intellibitz.com [email_address]
  • 7. Important definitions Session A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier. www.intellibitz.com [email_address]
  • 8. Important definitions Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer. www.intellibitz.com [email_address]
  • 9. Important definitions Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session. www.intellibitz.com [email_address]
  • 10. Important definitions Transaction (Optional) 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. However, transaction demarcation, either using the underlying API or Transaction, is never optional! www.intellibitz.com [email_address]
  • 11. Important definitions 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.l! www.intellibitz.com [email_address]
  • 12. Important definitions TransactionFactory (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer. www.intellibitz.com [email_address]
  • 13. Instance States Transient The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value). www.intellibitz.com [email_address]
  • 14. Instance States Persistent The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object). www.intellibitz.com [email_address]
  • 15. Instance States Detached The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corrsponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity. www.intellibitz.com [email_address]
  • 16. Configuration Programmatic configuration An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The Configuration is used to build an (immutable) SessionFactory. The mappings are compiled from various XML mapping files. www.intellibitz.com [email_address]
  • 17. Configuration obtain a Configuration instance by instantiating it directly and specifying XML mapping documents Configuration cfg = new Configuration() .addResource(&quot;Item.hbm.xml&quot;) .addResource(&quot;Bid.hbm.xml&quot;); www.intellibitz.com [email_address]
  • 18. Configuration An alternative (sometimes better) way is to specify the mapped class, and let Hibernate find the mapping document for you Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class); www.intellibitz.com [email_address]
  • 19. Configuration A Configuration also allows you to specify configuration properties: Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class) .setProperty(&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.MySQLDialect&quot;) .setProperty(&quot;hibernate.order_updates&quot;, &quot;true&quot;); www.intellibitz.com [email_address]
  • 20. Configuration Many ways to pass configuration properties: Pass an instance of java.util.Properties to Configuration.setProperties(). Place hibernate.properties in classpath. Set System properties using java -Dprop=val. Include <property> elements in hibernate.cfg.xml hibernate.properties is the easiest approach. Configuration is a startup-time object, to be discarded once a SessionFactory is created. www.intellibitz.com [email_address]
  • 21. Configuration Obtaining a SessionFactory After parsing all mappings by the Configuration, the application must obtain a factory for Session instances. This factory is intended to be shared by all application threads. SessionFactory sessions = cfg.buildSessionFactory(); your application can instantiate more than one SessionFactory. This is useful if you are using more than one database. www.intellibitz.com [email_address]
  • 22. Configuration JDBC connections Session session = sessions.openSession(); Hibernate will obtain (and pool) connections using java.sql.DriverManager if you set the following properties: www.intellibitz.com [email_address]
  • 23. Configuration hibernate.connection.driver_class jdbc driver class hibernate.connection.url jdbc URL hibernate.connection.username database user hibernate.connection.password database user password hibernate.connection.pool_size maximum number of pooled connections www.intellibitz.com [email_address]
  • 24. Connection Pool To use a third party pool for best performance and stability Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use C3P0. www.intellibitz.com [email_address]
  • 25. Connection Pool C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib directory. Hibernate will use its C3P0ConnectionProvider for connection pooling if you set hibernate.c3p0.* properties. www.intellibitz.com [email_address]
  • 26. Connection Pool Here is an example hibernate.properties file for C3P0: hibernate.connection.driver_class = org.postgresql.Driver hibernate.connection.url = jdbc:postgresql://localhost/mydatabase hibernate.connection.username = myuser hibernate.connection.password = secret hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statements=50 hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect www.intellibitz.com [email_address]
  • 27. Datasource For use inside an application server, configure Hibernate to obtain connections from an application server Datasource registered in JNDI. You'll need to set at least one of the following properties: hibernate.connection.datasource datasource JNDI name hibernate.jndi.url URL of the JNDI provider (optional) hibernate.jndi.class class of the JNDI InitialContextFactory (optional) hibernate.connection.username database user (optional) hibernate.connection.password database user password (optional) www.intellibitz.com [email_address]
  • 28. Datasource hibernate.properties file for an application server provided JNDI datasource: hibernate.connection.datasource = java:/comp/env/jdbc/test hibernate.transaction.factory_class = org.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = org.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect www.intellibitz.com [email_address]
  • 29. SQL Dialects always set the hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database. If you specify a dialect, Hibernate will use sensible defaults for some of the other properties listed above, saving you the effort of specifying them manually. www.intellibitz.com [email_address]
  • 30. XML configuration file An alternative approach to configuration is to specify a full configuration in a file named hibernate.cfg.xml. This file can be used as a replacement for the hibernate.properties file or, if both are present, to override properties. The XML configuration file is by default expected to be in the root of your CLASSPATH. www.intellibitz.com [email_address]
  • 31. XML configuration file <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;> <hibernate-configuration> <!-- a SessionFactory instance listed as /jndi/name --> <session-factory name=&quot;java:hibernate/SessionFactory&quot;> <!-- properties --> <property name=&quot;connection.datasource&quot;>java:/comp/env/jdbc/MyDB</property> <property name=&quot;dialect&quot;>org.hibernate.dialect.MySQLDialect</property> <property name=&quot;show_sql&quot;>false</property> <property name=&quot;transaction.factory_class&quot;> org.hibernate.transaction.JTATransactionFactory </property> <property name=&quot;jta.UserTransaction&quot;>java:comp/UserTransaction</property> <!-- mapping files --> <mapping resource=&quot;org/hibernate/auction/Item.hbm.xml&quot;/> <mapping resource=&quot;org/hibernate/auction/Bid.hbm.xml&quot;/> <!-- cache settings --> <class-cache class=&quot;org.hibernate.auction.Item&quot; usage=&quot;read-write&quot;/> <class-cache class=&quot;org.hibernate.auction.Bid&quot; usage=&quot;read-only&quot;/> <collection-cache collection=&quot;org.hibernate.auction.Item.bids&quot; usage=&quot;read-write&quot;/> </session-factory> </hibernate-configuration> www.intellibitz.com [email_address]
  • 32. XML configuration file With the XML configuration, starting Hibernate is then as simple as SessionFactory sf = new Configuration().configure().buildSessionFactory() pick a different XML configuration file using SessionFactory sf = new Configuration() .configure(&quot;catdb.cfg.xml&quot;) .buildSessionFactory(); www.intellibitz.com [email_address]
  • 33. Persistent Classes Persistent classes are classes that implement the entities of the business problem. Not all instances of a persistent class are considered to be in the persistent state - an instance may instead be transient or detached. Hibernate works best if these classes follow the Plain Old Java Object (POJO) model. www.intellibitz.com [email_address]
  • 34. Persistent Classes 4 simple rules to follow Implement a no-argument constructor Provide an identifier property (optional) Prefer non-final classes (optional) Declare accessors and mutators for persistent fields (optional) www.intellibitz.com [email_address]
  • 35. Persistent Classes Implementing equals() and hashCode() intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations) and intend to use reattachment of detached instances www.intellibitz.com [email_address]
  • 36. Persistent Classes Business key equality recommend implementing equals() and hashCode() using Business key equality. Business key equality means that the equals() method compares only the properties that form the business key, a key that would identify our instance in the real world (a natural candidate key) www.intellibitz.com [email_address]
  • 37. Persistent Classes Business key equality public class Cat { ... public boolean equals(Object other) { if (this == other) return true; if ( !(other instanceof Cat) ) return false; final Cat cat = (Cat) other; if ( !cat.getLitterId().equals( getLitterId() ) ) return false; if ( !cat.getMother().equals( getMother() ) ) return false; return true; } public int hashCode() { int result; result = getMother().hashCode(); result = 29 * result + getLitterId(); return result; } } www.intellibitz.com [email_address]
  • 38. Basic O/R Mapping Mapping declaration O/R mappings are defined in an XML document. designed to be readable and hand-editable. Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations. many users write the XML by hand, but a number of tools exist to generate the mapping, including XDoclet, Middlegen and AndroMDA. www.intellibitz.com [email_address]
  • 39. Basic O/R Mapping <?xml version=&quot;1.0&quot;?> <!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;> <hibernate-mapping package=&quot;eg&quot;> <class name=&quot;Cat&quot; table=&quot;cats&quot; discriminator-value=&quot;C&quot;> <id name=&quot;id&quot;> <generator class=&quot;native&quot;/> </id> <discriminator column=&quot;subclass&quot; type=&quot;character&quot;/> <property name=&quot;weight&quot;/> <property name=&quot;birthdate&quot; type=&quot;date&quot; not-null=&quot;true&quot; update=&quot;false&quot;/> <property name=&quot;color&quot; type=&quot;eg.types.ColorUserType&quot; not-null=&quot;true&quot; update=&quot;false&quot;/> www.intellibitz.com [email_address] <property name=&quot;sex&quot; not-null=&quot;true&quot; update=&quot;false&quot;/> <property name=&quot;litterId&quot; column=&quot;litterId&quot; update=&quot;false&quot;/> <many-to-one name=&quot;mother&quot; column=&quot;mother_id&quot; update=&quot;false&quot;/> <set name=&quot;kittens&quot; inverse=&quot;true&quot; order-by=&quot;litter_id&quot;> <key column=&quot;mother_id&quot;/> <one-to-many class=&quot;Cat&quot;/> </set> <subclass name=&quot;DomesticCat&quot; discriminator-value=&quot;D&quot;> <property name=&quot;name&quot; type=&quot;string&quot;/> </subclass> </class> <class name=&quot;Dog&quot;> <!-- mapping for Dog could go here --> </class> </hibernate-mapping>
  • 40. Basic O/R Mapping class <class name=&quot;ClassName&quot; (1) table=&quot;tableName&quot; (2) discriminator-value=&quot;discriminator_value&quot; (3) mutable=&quot;true|false&quot; (4) schema=&quot;owner&quot; (5) catalog=&quot;catalog&quot; (6) proxy=&quot;ProxyInterface&quot; (7) dynamic-update=&quot;true|false&quot; (8) dynamic-insert=&quot;true|false&quot; (9) select-before-update=&quot;true|false&quot; (10) polymorphism=&quot;implicit|explicit&quot; (11) where=&quot;arbitrary sql where condition&quot; (12) persister=&quot;PersisterClass&quot; (13) batch-size=&quot;N&quot; (14) optimistic-lock=&quot;none|version|dirty|all&quot; (15) lazy=&quot;true|false&quot; (16) entity-name=&quot;EntityName&quot; (17) check=&quot;arbitrary sql check condition&quot; (18) rowid=&quot;rowid&quot; (19) subselect=&quot;SQL expression&quot; (20) abstract=&quot;true|false&quot; (21) node=&quot;element-name&quot; /> www.intellibitz.com [email_address]
  • 41. Basic O/R Mapping id <id name=&quot;propertyName&quot; (1) type=&quot;typename&quot; (2) column=&quot;column_name&quot; (3) unsaved-value=&quot;null|any|none|undefined|id_value&quot; (4) access=&quot;field|property|ClassName&quot;> (5) node=&quot;element-name|@attribute-name|element/@attribute|.&quot; <generator class=&quot;generatorClass&quot;/> </id> generator <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;cat_id&quot;> <generator class=&quot;org.hibernate.id.TableHiLoGenerator&quot;> <param name=&quot;table&quot;>uid_table</param> <param name=&quot;column&quot;>next_hi_value_column</param> </generator> </id> www.intellibitz.com [email_address]
  • 42. Basic O/R Mapping property <property name=&quot;propertyName&quot; (1) column=&quot;column_name&quot; (2) type=&quot;typename&quot; (3) update=&quot;true|false&quot; (4) insert=&quot;true|false&quot; (4) formula=&quot;arbitrary SQL expression&quot; (5) access=&quot;field|property|ClassName&quot; (6) lazy=&quot;true|false&quot; (7) unique=&quot;true|false&quot; (8) not-null=&quot;true|false&quot; (9) optimistic-lock=&quot;true|false&quot; (10) generated=&quot;never|insert|always&quot; (11) node=&quot;element-name|@attribute-name|element/@attribute|.&quot; index=&quot;index_name&quot; unique_key=&quot;unique_key_id&quot; length=&quot;L&quot; precision=&quot;P&quot; scale=&quot;S&quot; /> www.intellibitz.com [email_address]
  • 43. Basic O/R Mapping many-to-one An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a many-to-one association: a foreign key in one table is referencing the primary key column(s) of the target table. <many-to-one name=&quot;product&quot; class=&quot;Product&quot; column=&quot;PRODUCT_ID&quot;/> www.intellibitz.com [email_address]
  • 44. Basic O/R Mapping one-to-one There are two varieties of one-to-one association: primary key associations unique foreign key associations www.intellibitz.com [email_address]
  • 45. Basic O/R Mapping one-to-one Primary key associations don't need an extra table column; if two rows are related by the association then the two table rows share the same primary key value. So if you want two objects to be related by a primary key association, you must make sure that they are assigned the same identifier value! www.intellibitz.com [email_address]
  • 46. Basic O/R Mapping one-to-one <class name=&quot;person&quot; table=&quot;PERSON&quot;> <id name=&quot;id&quot; column=&quot;PERSON_ID&quot;> <generator class=&quot;foreign&quot;> <param name=&quot;property&quot;>employee</param> </generator> </id> ... <one-to-one name=&quot;employee&quot; class=&quot;Employee&quot; constrained=&quot;true&quot;/> </class> www.intellibitz.com [email_address]
  • 47. Hibernate Types Entities and Values An entity exists independently of any other objects holding references to the entity. Contrast this with the usual Java model where an unreferenced object is garbage collected. Entities must be explicitly saved and deleted (except that saves and deletions may be cascaded from a parent entity to its children). Entities support circular and shared references. They may also be versioned. www.intellibitz.com [email_address]
  • 48. Hibernate Types Entities and Values Values are primitives, collections (not what's inside a collection), components and certain immutable objects. Unlike entities, values (in particular collections and components) are persisted and deleted by reachability. Since value objects (and primitives) are persisted and deleted along with their containing entity they may not be independently versioned. Values have no independent identity, so they cannot be shared by two entities or collections. www.intellibitz.com [email_address]
  • 49. Hibernate Types Entities and Values Entities are mapped by <class>, <subclass> and so on. For value types we use <property>, <component>, etc, usually with a type attribute. www.intellibitz.com [email_address]
  • 50. Jdk 5 Annotations @Entity(access = AccessType.FIELD) public class Customer implements Serializable { @Id; Long id; String firstName; String lastName; Date birthday; @Transient Integer age; @Embedded private Address homeAddress; @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name=&quot;CUSTOMER_ID&quot;) Set<Order> orders; // Getter/setter and business methods } www.intellibitz.com [email_address]
  • 51. Collection Mapping Persistent collections Hibernate requires that persistent collection-valued fields be declared as an interface type. Ex: private Set parts = new HashSet(); When you make the instance persistent - by calling persist(), for example - Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set. www.intellibitz.com [email_address]
  • 52. Collection Mapping Persistent collections Watch out for errors like this: Cat cat = new DomesticCat(); Cat kitten = new DomesticCat(); .... Set kittens = new HashSet(); kittens.add(kitten); cat.setKittens(kittens); session.persist(cat); kittens = cat.getKittens(); // Okay, kittens collection is a Set (HashSet) cat.getKittens(); // Error! Collections instances have the usual behavior of value types. Two entities may not share a reference to the same collection instance. www.intellibitz.com [email_address]
  • 53. Collection Mapping <class name=&quot;Product&quot;> <id name=&quot;serialNumber&quot; column=&quot;productSerialNumber&quot;/> <set name=&quot;parts&quot;> <key column=&quot;productSerialNumber&quot; not-null=&quot;true&quot;/> <one-to-many class=&quot;Part&quot;/> </set> </class> <set name=&quot;names&quot; table=&quot;person_names&quot;> <key column=&quot;person_id&quot;/> <element column=&quot;person_name&quot; type=&quot;string&quot;/> </set> <array name=&quot;addresses&quot; table=&quot;PersonAddress&quot; cascade=&quot;persist&quot;> <key column=&quot;personId&quot;/> <list-index column=&quot;sortOrder&quot;/> <many-to-many column=&quot;addressId&quot; class=&quot;Address&quot;/> </array> www.intellibitz.com [email_address]
  • 54. Collection Mapping Bidirectional associations one-to-many set or bag valued at one end, single-valued at the other many-to-many set or bag valued at both ends www.intellibitz.com [email_address]
  • 55. Collection Mapping Bidirectional associations many-to-many example <class name=&quot;Category&quot;> <id name=&quot;id&quot; column=&quot;CATEGORY_ID&quot;/> ... <bag name=&quot;items&quot; table=&quot;CATEGORY_ITEM&quot;> <key column=&quot;CATEGORY_ID&quot;/> <many-to-many class=&quot;Item&quot; column=&quot;ITEM_ID&quot;/> </bag> </class> <class name=&quot;Item&quot;> <id name=&quot;id&quot; column=&quot;CATEGORY_ID&quot;/> ... <!-- inverse end --> <bag name=&quot;categories&quot; table=&quot;CATEGORY_ITEM&quot; inverse=&quot;true&quot;> <key column=&quot;ITEM_ID&quot;/> <many-to-many class=&quot;Category&quot; column=&quot;CATEGORY_ID&quot;/> </bag> </class> www.intellibitz.com [email_address]
  • 56. Collection Mapping Bidirectional associations Changes made only to the inverse end of the association are not persisted. This means that Hibernate has two representations in memory for every bidirectional association, one link from A to B and another link from B to A. category.getItems().add(item); // The category now &quot;knows&quot; about the relationship item.getCategories().add(category); // The item now &quot;knows&quot; about the relationship session.persist(item); // The relationship won't be saved! session.persist(category); // The relationship will be saved The non-inverse side is used to save the in-memory representation to the database. www.intellibitz.com [email_address]
  • 57. Association Mappings Unidirectional associations many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 58. Association Mappings Unidirectional associations one to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot; unique=&quot;true&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key, addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 59. Association Mappings Unidirectional associations with join tables one to many <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot; table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; unique=&quot;true&quot; class=&quot;Address&quot;/> </set> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId not null, addressId bigint not null primary key ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 60. Association Mappings Unidirectional associations with join tables many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot; optional=&quot;true&quot;> <key column=&quot;personId&quot; unique=&quot;true&quot;/> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot; not-null=&quot;true&quot;/> </join> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 61. Association Mappings Unidirectional associations with join tables many to many <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot; table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; class=&quot;Address&quot;/> </set> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 62. Association Mappings Bidirectional associations one to many / many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;people&quot; inverse=&quot;true&quot;> <key column=&quot;addressId&quot;/> <one-to-many class=&quot;Person&quot;/> </set> </class> create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 63. Association Mappings Bidirectional associations one to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot; unique=&quot;true&quot; not-null=&quot;true&quot;/> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <one-to-one name=&quot;person&quot; property-ref=&quot;address&quot;/> </class> create table Person ( personId bigint not null primary key, addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 64. Association Mappings Bidirectional associations with join tables one to many / many to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot; table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; unique=&quot;true&quot; class=&quot;Address&quot;/> </set> </class> www.intellibitz.com [email_address] <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot; inverse=&quot;true&quot; optional=&quot;true&quot;> <key column=&quot;addressId&quot;/> <many-to-one name=&quot;person&quot; column=&quot;personId&quot; not-null=&quot;true&quot;/> </join> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null, addressId bigint not null primary key ) create table Address ( addressId bigint not null primary key )
  • 65. Association Mappings Bidirectional associations with join tables one to one <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot; optional=&quot;true&quot;> <key column=&quot;personId&quot; unique=&quot;true&quot;/> <many-to-one name=&quot;address&quot; column=&quot;addressId&quot; not-null=&quot;true&quot; unique=&quot;true&quot;/> </join> </class> www.intellibitz.com [email_address] <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <join table=&quot;PersonAddress&quot; optional=&quot;true&quot; inverse=&quot;true&quot;> <key column=&quot;addressId&quot; unique=&quot;true&quot;/> <many-to-one name=&quot;person&quot; column=&quot;personId&quot; not-null=&quot;true&quot; unique=&quot;true&quot;/> </join> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null primary key, addressId bigint not null unique ) create table Address ( addressId bigint not null primary key )
  • 66. Association Mappings Bidirectional associations with join tables many to many <class name=&quot;Person&quot;> <id name=&quot;id&quot; column=&quot;personId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;addresses&quot; table=&quot;PersonAddress&quot;> <key column=&quot;personId&quot;/> <many-to-many column=&quot;addressId&quot; class=&quot;Address&quot;/> </set> </class> <class name=&quot;Address&quot;> <id name=&quot;id&quot; column=&quot;addressId&quot;> <generator class=&quot;native&quot;/> </id> <set name=&quot;people&quot; inverse=&quot;true&quot; table=&quot;PersonAddress&quot;> <key column=&quot;addressId&quot;/> <many-to-many column=&quot;personId&quot; class=&quot;Person&quot;/> </set> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) ) create table Address ( addressId bigint not null primary key ) www.intellibitz.com [email_address]
  • 67. Component Mapping Dependent Objects A component is a contained object that is persisted as a value type, not an entity reference. The term &quot;component&quot; refers to the object-oriented notion of composition (not to architecture-level components). www.intellibitz.com [email_address]
  • 68. Component Mapping public class Person { private java.util.Date birthday; private Name name; private String key; public String getKey() { return key; } private void setKey(String key) { this.key=key; } public java.util.Date getBirthday() { return birthday; } public void setBirthday(java.util.Date birthday) { this.birthday = birthday; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } ...... ...... } www.intellibitz.com [email_address] public class Name { char initial; String first; String last; public String getFirst() { return first; } void setFirst(String first) { this.first = first; } public String getLast() { return last; } void setLast(String last) { this.last = last; } public char getInitial() { return initial; } void setInitial(char initial) { this.initial = initial; } }
  • 69. Component Mapping Hibernate mapping: <class name=&quot;eg.Person&quot; table=&quot;person&quot;> <id name=&quot;Key&quot; column=&quot;pid&quot; type=&quot;string&quot;> <generator class=&quot;uuid&quot;/> </id> <property name=&quot;birthday&quot; type=&quot;date&quot;/> <component name=&quot;Name&quot; class=&quot;eg.Name&quot;> <!-- class attribute optional --> <property name=&quot;initial&quot;/> <property name=&quot;first&quot;/> <property name=&quot;last&quot;/> </component> </class> The person table would have the columns pid, birthday, initial, first and last. www.intellibitz.com [email_address]
  • 70. Component Mapping Collections of dependent objects Collections of components are supported (eg. an array of type Name). Declare your component collection by replacing the <element> tag with a <composite-element> tag. <set name=&quot;someNames&quot; table=&quot;some_names&quot; lazy=&quot;true&quot;> <key column=&quot;id&quot;/> <composite-element class=&quot;eg.Name&quot;> <!-- class attribute required --> <property name=&quot;initial&quot;/> <property name=&quot;first&quot;/> <property name=&quot;last&quot;/> </composite-element> </set> www.intellibitz.com [email_address]
  • 71. Inheritance Mapping The Three Strategies * table per class hierarchy table per subclass table per concrete class supports a fourth, slightly different kind of polymorphism: implicit polymorphism www.intellibitz.com [email_address]
  • 72. Inheritance Mapping Table per class hierarchy Exactly one table is required. one big limitation of this mapping strategy: columns declared by the subclasses, such as CCTYPE, may not have NOT NULL constraints. www.intellibitz.com [email_address] <class name=&quot;Payment&quot; table=&quot;PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <discriminator column=&quot;PAYMENT_TYPE&quot; type=&quot;string&quot;/> <property name=&quot;amount&quot; column=&quot;AMOUNT&quot;/> ... <subclass name=&quot;CreditCardPayment&quot; discriminator-value=&quot;CREDIT&quot;> <property name=&quot;creditCardType&quot; column=&quot;CCTYPE&quot;/> ... </subclass> <subclass name=&quot;CashPayment&quot; discriminator-value=&quot;CASH&quot;> ... </subclass> <subclass name=&quot;ChequePayment&quot; discriminator-value=&quot;CHEQUE&quot;> ... </subclass> </class>
  • 73. Inheritance Mapping Table per subclass Four tables are required. The three subclass tables have primary key associations to the superclass table (so the relational model is actually a one-to-one association). www.intellibitz.com [email_address] <class name=&quot;Payment&quot; table=&quot;PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;AMOUNT&quot;/> ... <joined-subclass name=&quot;CreditCardPayment&quot; table=&quot;CREDIT_PAYMENT&quot;> <key column=&quot;PAYMENT_ID&quot;/> <property name=&quot;creditCardType&quot; column=&quot;CCTYPE&quot;/> ... </joined-subclass> <joined-subclass name=&quot;CashPayment&quot; table=&quot;CASH_PAYMENT&quot;> <key column=&quot;PAYMENT_ID&quot;/> ... </joined-subclass> <joined-subclass name=&quot;ChequePayment&quot; table=&quot;CHEQUE_PAYMENT&quot;> <key column=&quot;PAYMENT_ID&quot;/> ... </joined-subclass> </class>
  • 74. Inheritance Mapping Table per concrete class Three tables are involved for the subclasses. Each table defines columns for all properties of the class, including inherited properties. The limitation of this approach is that if a property is mapped on the superclass, the column name must be the same on all subclass tables. If your superclass is abstract, map it with abstract=&quot;true&quot;. Of course, if it is not abstract, an additional table (defaults to PAYMENT in the example above) is needed to hold instances of the superclass. www.intellibitz.com [email_address] <class name=&quot;Payment&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;PAYMENT_ID&quot;> <generator class=&quot;sequence&quot;/> </id> <property name=&quot;amount&quot; column=&quot;AMOUNT&quot;/> ... <union-subclass name=&quot;CreditCardPayment&quot; table=&quot;CREDIT_PAYMENT&quot;> <property name=&quot;creditCardType&quot; column=&quot;CCTYPE&quot;/> ... </union-subclass> <union-subclass name=&quot;CashPayment&quot; table=&quot;CASH_PAYMENT&quot;> ... </union-subclass> <union-subclass name=&quot;ChequePayment&quot; table=&quot;CHEQUE_PAYMENT&quot;> ... </union-subclass> </class>
  • 75. Inheritance Mapping Table per concrete class using implicit polymorphism Notice that nowhere do we mention the Payment interface explicitly. Also notice that properties of Payment are mapped in each of the subclasses. If you want to avoid duplication, consider using XML entities The disadvantage of this approach is that Hibernate does not generate SQL UNIONs when performing polymorphic queries. For this mapping strategy, a polymorphic association to Payment is usually mapped using <any>. www.intellibitz.com [email_address] <class name=&quot;CreditCardPayment&quot; table=&quot;CREDIT_PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;CREDIT_PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;CREDIT_AMOUNT&quot;/> ... </class> <class name=&quot;CashPayment&quot; table=&quot;CASH_PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;CASH_PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;CASH_AMOUNT&quot;/> ... </class> <class name=&quot;ChequePayment&quot; table=&quot;CHEQUE_PAYMENT&quot;> <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;CHEQUE_PAYMENT_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;amount&quot; column=&quot;CHEQUE_AMOUNT&quot;/> ... </class>
  • 76. Working with Objects Hibernate Object states Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Use the Hibernate Session to make an object persistent (and let Hibernate take care SQL statements to be executed for this transition). www.intellibitz.com [email_address]
  • 77. Working with Objects Hibernate Object states Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. www.intellibitz.com [email_address]
  • 78. Working with Objects Hibernate Object states Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. www.intellibitz.com [email_address]
  • 79. Working with Objects Making Objects Persistent a transient instance becomes persistent by associating it with a session: DomesticCat fritz = new DomesticCat(); fritz.setColor(Color.GINGER); fritz.setSex('M'); fritz.setName(&quot;Fritz&quot;); Long generatedId = (Long) sess.save(fritz); If Cat has a generated identifier, the identifier is generated and assigned to the cat when save() is called. If Cat has an assigned identifier, or a composite key, the identifier should be assigned to the cat instance before calling save(). www.intellibitz.com [email_address]
  • 80. Working with Objects Loading an Object use load() to retrieve a persistent instance by its identifier. load() takes a class object and will load the state into a newly instantiated instance of that class, in persistent state. Cat fritz = (Cat) sess.load(Cat.class, generatedId); If not certain that a matching row exists, use get(), which hits the database immediately and returns null if there is no matching row. www.intellibitz.com [email_address]
  • 81. Working with Objects Querying Hibernate supports an easy-to-use but powerful object oriented query language (HQL). For programmatic query creation, Hibernate supports a sophisticated Criteria and Example query feature (QBC and QBE). You may also express your query in the native SQL of your database, with optional support from Hibernate for result set conversion into objects. www.intellibitz.com [email_address]
  • 82. Working with Objects Executing Queries HQL and native SQL queries are represented with an instance of org.hibernate.Query. This interface offers methods for parameter binding, result set handling, and for the execution of the actual query. You always obtain a Query using the current Session: List mothers = session.createQuery( &quot;select mother from Cat as cat join cat.mother as mother where cat.name = ?&quot;) .setString(0, name) .list(); www.intellibitz.com [email_address]
  • 83. Working with Objects Executing Queries A query is usually executed by invoking list(), the result loaded completely into a collection in memory. Entity instances retrieved by a query are in persistent state. The uniqueResult() method offers a shortcut if you know your query will only return a single object. www.intellibitz.com [email_address]
  • 84. Working with Objects Iterating results Occasionally, executing the query using the iterate() method is faster. This will only usually be the case if you expect that the actual entity instances returned by the query will already be in the session or second-level cache. If they are not already cached, iterate() will be slower than list() and might require many database hits for a simple query. www.intellibitz.com [email_address]
  • 85. Working with Objects Queries that return tuples Hibernate queries sometimes return tuples of objects, in which case each tuple is returned as an array: Iterator kittensAndMothers = sess.createQuery( &quot;select kitten, mother from Cat kitten join kitten.mother mother&quot;) .list() .iterator(); while ( kittensAndMothers.hasNext() ) { Object[] tuple = (Object[]) kittensAndMothers.next(); Cat kitten = tuple[0]; Cat mother = tuple[1]; .... } www.intellibitz.com [email_address]
  • 86. Working with Objects Scalar results Queries may specify a property of a class in the select clause. They may even call SQL aggregate functions. Properties or aggregates are considered &quot;scalar&quot; results. Iterator results = sess.createQuery( &quot;select cat.color, min(cat.birthdate), count(cat) from Cat cat &quot; + &quot;group by cat.color&quot;) .list() .iterator(); while ( results.hasNext() ) { Object[] row = (Object[]) results.next(); Color type = (Color) row[0]; Date oldest = (Date) row[1]; Integer count = (Integer) row[2]; ..... } www.intellibitz.com [email_address]
  • 87. Working with Objects Bind Parameters Contrary to JDBC, Hibernate numbers parameters from zero. Named parameters are identifiers of the form :name in the query string. The advantages of named parameters are: named parameters are insensitive to the order they occur in the query string they may occur multiple times in the same query they are self-documenting www.intellibitz.com [email_address]
  • 88. Working with Objects Bind Parameters //named parameter (preferred) Query q = sess.createQuery(&quot;from DomesticCat cat where cat.name = :name&quot;); q.setString(&quot;name&quot;, &quot;Fritz&quot;); Iterator cats = q.iterate(); //positional parameter Query q = sess.createQuery(&quot;from DomesticCat cat where cat.name = ?&quot;); q.setString(0, &quot;Izi&quot;); Iterator cats = q.iterate(); //named parameter list List names = new ArrayList(); names.add(&quot;Izi&quot;); names.add(&quot;Fritz&quot;); Query q = sess.createQuery(&quot;from DomesticCat cat where cat.name in (:namesList)&quot;); q.setParameterList(&quot;namesList&quot;, names); List cats = q.list(); www.intellibitz.com [email_address]
  • 89. Working with Objects Pagination If you need to specify bounds upon your result set (the maximum number of rows you want to retrieve and / or the first row you want to retrieve) you should use methods of the Query interface: Query q = sess.createQuery(&quot;from DomesticCat cat&quot;); q.setFirstResult(20); q.setMaxResults(10); List cats = q.list(); Hibernate knows how to translate this limit query into the native SQL of your DBMS. www.intellibitz.com [email_address]
  • 90. Working with Objects Externalizing named queries named queries in the mapping document. <query name=&quot;ByNameAndMaximumWeight&quot;><![CDATA[ from eg.DomesticCat as cat where cat.name = ? and cat.weight > ? ] ]></query> Parameter binding done programatically: Query q = sess.getNamedQuery (&quot;ByNameAndMaximumWeight&quot;); q.setString(0, name); q.setInt(1, minWeight); List cats = q.list(); may also define native SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files. www.intellibitz.com [email_address]
  • 91. Working with Objects Externalizing named queries Note that the actual program code is independent of the query language that is used as said above. Also note that a query declaration inside a <hibernate-mapping> element requires a global unique name for the query, while a query declaration inside a <class> element is made unique automatically by prepending the fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight. www.intellibitz.com [email_address]
  • 92. Working with Objects Filtering Collections A collection filter may be applied to a persistent collection or array. The query string may refer to this, meaning the current collection element. Collection blackKittens = session.createFilter( pk.getKittens(), &quot;where this.color = ?&quot;) .setParameter( Color.BLACK, Hibernate.custom(ColorUserType.class) ) .list() ); The returned collection is a copy of the given collection. The original collection is not modified. Observe that filters do not require a from clause (though they may have one if required). www.intellibitz.com [email_address]
  • 93. Working with Objects Criteria queries HQL is extremely powerful but some developers prefer to build queries dynamically, using an object-oriented API, rather than building query strings. Hibernate provides an intuitive Criteria query API for these cases: Criteria crit = session.createCriteria(Cat.class); crit.add( Expression.eq( &quot;color&quot;, eg.Color.BLACK ) ); crit.setMaxResults(10); List cats = crit.list(); www.intellibitz.com [email_address]
  • 94. Working with Objects Queries in native SQL You may express a query in SQL, using createSQLQuery() and let Hibernate take care of the mapping from result sets to objects. Note that you may at any time call session.connection() and use the JDBC Connection directly. If you chose to use the Hibernate API, you must enclose SQL aliases in braces: List cats = session.createSQLQuery( &quot;SELECT {cat.*} FROM CAT {cat} WHERE ROWNUM<10&quot;, &quot;cat&quot;, Cat.class).list(); www.intellibitz.com [email_address]
  • 95. Working with Objects Modifying Persistent Objects Transactional persistent instances (ie. objects loaded, saved, created or queried by the Session) may be manipulated by the application and any changes to persistent state will be persisted when the Session is flushed. So the most straightforward way to update the state of an object is to load() it, and then manipulate it directly, while the Session is open: DomesticCat cat = (DomesticCat) sess.load( Cat.class, new Long(69) ); cat.setName(&quot;PK&quot;); sess.flush(); // changes to cat are automatically detected and persisted www.intellibitz.com [email_address]
  • 96. Working with Objects Modifying detached Objects Hibernate supports for reattachment of detached instances using the Session.update() or Session.merge() methods: // in the first session Cat cat = (Cat) firstSession.load(Cat.class, catId); Cat potentialMate = new Cat(); firstSession.save(potentialMate); // in a higher layer of the application cat.setMate(potentialMate); // later, in a new session secondSession.update(cat); // update cat secondSession.update(mate); // update mate www.intellibitz.com [email_address]
  • 97. Working with Objects Modifying detached Objects Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session. In other words, update() is usually the first method you would call in a fresh session, ensuring that reattachment of your detached instances is the first operation that is executed. www.intellibitz.com [email_address]
  • 98. Working with Objects Modifying detached Objects The lock() method also allows an application to reassociate an object with a new session. However, the detached instance has to be unmodified! //just reassociate: sess.lock(fritz, LockMode.NONE); //do a version check, then reassociate: sess.lock(izi, LockMode.READ); //do a version check, using SELECT ... FOR UPDATE, then reassociate: sess.lock(pk, LockMode.UPGRADE); www.intellibitz.com [email_address]
  • 99. Working with Objects Automatic State detection The saveOrUpdate() is a general purpose method that either saves a transient instance by generating a new identifier or updates/reattaches the detached instances associated with its current identifier. // in the first session Cat cat = (Cat) firstSession.load(Cat.class, catID); // in a higher tier of the application Cat mate = new Cat(); cat.setMate(mate); // later, in a new session secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id) secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id) www.intellibitz.com [email_address]
  • 100. Working with Objects Automatic State detection Usually update() or saveOrUpdate() are used in the following scenario: the application loads an object in the first session the object is passed up to the UI tier some modifications are made to the object the object is passed back down to the business logic tier the application persists these modifications by calling update() in a second session www.intellibitz.com [email_address]
  • 101. Working with Objects Automatic State detection saveOrUpdate() does the following: if the object is already persistent in this session, do nothing if another object associated with the session has the same identifier, throw an exception if the object has no identifier property, save() it if the object's identifier has the value assigned to a newly instantiated object, save() it if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it otherwise update() the object www.intellibitz.com [email_address]
  • 102. Working with Objects Automatic State detection merge() does the following: if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance the persistent instance is returned the given instance does not become associated with the session, it remains detached www.intellibitz.com [email_address]
  • 103. Working with Objects Deleting Persistent Objects Session.delete() will remove an object's state from the database. It's best to think of delete() as making a persistent instance transient. sess.delete(cat); You may delete objects in any order you like, without risk of foreign key constraint violations. It is still possible to violate a NOT NULL constraint on a foreign key column by deleting objects in the wrong order, e.g. if you delete the parent, but forget to delete the children. www.intellibitz.com [email_address]
  • 104. Working with Objects Flushing the Session From time to time the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points before some query executions from org.hibernate.Transaction.commit() from Session.flush() www.intellibitz.com [email_address]
  • 105. Working with Objects Transitive Persistence It is quite cumbersome to save, delete, or reattach individual objects, especially if you deal with a graph of associated objects. A common case is a parent/child relationship. Hibernate does not implement persistence by reachability by default. If you want an operation to be cascaded along an association, you must indicate that in the mapping document using 'cascade'. www.intellibitz.com [email_address]