Issuu on Google+





XML Mapping files are: 1) Configuration files contains information about database like: driver, url, dialect, etc. 2) Mapping files contains information about how a domain model is mapped to relational model. Instead of XML Mapping files, annotations can also be used. However the entire contents are coverd only using XML mappings.


Hibernate searches for a configuration file named “hibernate.cfg.xml” in the root of the classpath, and an exception is thrown if it can’t be found.


The Configuration is meant only as an initialization-time object. The default configuration file is “hibernate.cfg.xml”. This file should be present in classpath. In scenarios where we need more than one database we may need more configuration files. One configuration file for one database, then you need to explicitly pass the configuration resource as argument to configure() method. Configuration cfg = new Configuration(); cfg.configure(“fileName.cfg.xml”); Configuration object is created using information present in “fileName.cfg.xml” Useful when more than one database is required.



Usually an application will create a single Configuration, build a single instance of SessionFactory and then instantiate Sessions in threads servicing client requests.


public Transaction beginTransaction() throws HibernateException •Begin a unit of work and return the associated Transaction object. •If a new underlying transaction is required, begin the transaction. •Otherwise continue the new work in the context of the existing underlying transaction. •The class of the returned Transaction object is determined by the property hibernate.transaction_factory_class. hibernate.transaction.factory_class: The classname of a TransactionFactory to use with Hibernate Transaction API(defaults to JDBCTransactionFactory).


Using Configuration object create a instance of SessionFactory. SessionFactory is used to create Session instances. Each Session can zero or more transactions. Note: Do not confuse Hibernate Session’s with HttpSession, they are meant for different purpose.


Book.hbm.xml 1) package (optional): Specifies a package prefix to assume for unqualified class names in the mapping document. 2) table (optional): If this attribute is not specified, table name will be same as unqualified name of the POJO class. 3) The class element should have <id> or <composite-id> for selecting a PRIMARY KEY or COMPOSITE PRIMARY KEY. 4) Generators are explained later. 5) The <property> element is used to map a java bean property to a table column. By default each property is accessed by hibernate using accessor methods (getters/setters). a. Attribute column(optional): If column attribute is not mentioned, column name will be same as that of field name. b. Attribute type (optional): The type mentioned is not java nor SQL type, it is hibernate type used to map Java type to SQL type based on the dialect selected in configuration file. c. All other constraints like unique, not-null can be applied to the column. Note: The â&#x20AC;&#x153;hbmâ&#x20AC;? suffix is a naming convention accepted by the Hibernate community, and preferably place mapping files next to the source code of their domain classes. 12

Libraries required: 1) hibernate3.jar : contains all the core hibernate files 2) mysql-connector-java-5.1.7-bin.jar: database specific jar 3) c3p0-0.9.1.jar: Connection and statement pooling 4) cglib-2.1.3.jar: Code Generation Library. Hibernate uses cglib to generate proxies for persistent classes. â&#x20AC;˘ New version of Hibernate uses javaassist instead of cglib.jar â&#x20AC;˘ Refer: explains why cglib is replaced with javaassist.jar 5. log4j-1.2.11.jar: To enable logging 6. asm.jar and asm-attrs.jar: Java bytecode manipulation along with cglib 7. ant.version.jar and ant-antlr.version.jar : used to parse XML 8. commons-collections.[version].jar :Apache commons-collections to build upon the Java collection framework by providing new interfaces, implementations and utilities 9. xerces.[version].jar: Xml processing.


Note : You should not set “bookId”, because in the mapping file generator class is specified as “increment”. If generator class is specified as “assigned” then programmatically “bookId” should be assigned.





• Serializable save(Object object) Persist the given transient instance, return a generated identifier. Generates INSERT SQL • void persist(Object object) Make a transient instance persistent. Generates INSERT SQL.

• Object get(Class clazz, Serializable id) Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. •Object load(Class theClass, Serializable id) throws HibernateException Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists. You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where nonexistence would be an actual error.

•void delete(Object object) throws HibernateException Remove a persistent instance from the datastore. •The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state. •void update(Object object) throws HibernateException •Update the persistent instance with the identifier of the given detached instance.


Transient objects : Objects instantiated using the new operator arenâ&#x20AC;&#x2122;t immediately persistent. Their state is transient, which means they arenâ&#x20AC;&#x2122;t associated with any database table row. Persistent objects: A persistent instance is an entity instance with a database identity. That means a persistent and managed instance has a primary key value set as its database identifier. Persistent instances are always associated with a Hibernate Session. Hibernate caches them and can detect whether they have been modified by the application. Detached objects: Detached Objects state is no longer guaranteed to be synchronized with database state; theyâ&#x20AC;&#x2122;re no longer attached to a Hibernate Session. They still contain persistent data (which may soon be stale). You can continue working with a detached object and modify it. Removed objects: Removed Objects will be deleted from the database as soon as the unit of work completes. Note:


•session.get (Book.class, 2L) •The arguments to this get methods are •the entity class Book •Primary Key 2L. PRIMARY KEY class has to implement Serializable interface.


For the specified ID if no ROW is found you get :org.hibernate.ObjectNotFoundException: No row with the given identifier exists Note: get() returns null if no row is found for the specified ID.


SELECT statement is not generated because session is closed. Hibernate Session is responsible for generating all Data Manipulation Language (DML) statements.



Detached objects: Detached Objects state is no longer guaranteed to be synchronized with database state; they’re no longer attached to a Hibernate Session. They still contain persistent data (which may soon be stale). You can continue working with a detached object and modify it. If a different object with the same identifier value was already associated with the session while updating an detached object “org.hibernate.NonUniqueObjectException” will be thrown. This is because Hibernate is trying to reinforce the guarantee that only a single instance of a Persistent object exist in memory. Refer Video tutorial to find more on NoUniqueObjectFoundException.


The merge() method is a little complex and works differently depending on what is in the persistence context. Hibernate will first check whether a Persistent instance of that type already exists in the persistent context. It uses the object identifiers to check on this existence. If another instance exists, it copies the state of the Detached object (p1 above) into the existing Persistence object (p2 above). If no other instance exists Hibernate just reattaches the Detached object.



Should we get the object into session before we delete? YES: Hibernate application will be configured to go through Hibernate Interceptors. Any operations we do not want to bypass these interceptors. Although there are ways to delete a row without getting that object into session. This will be discussed later.

After deleting it is good to set the identifier to â&#x20AC;&#x153;nullâ&#x20AC;?, because you can reattach a deleted object. Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Book bookRef = (Book) session.get(Book.class, 1L); session.delete(bookRef); tx.commit(); //bookRef is now Detached and deleted bookRef.setBookId(null);





Answers: 1)


2) org.hibernate.Session 3) Depending the dialect Hibernate generates appropriate SQLâ&#x20AC;&#x2122;s required to interact with the database.


Answers 4) At the line book.getTitle() we encounter NullPointerException. Reason : get() returns null if row with that identifer is not found. 5) At the line book.getTitle() we encounter ObjectNotFoundException. Reason: load() returns a proxy and hence it cannot be null. When you start accessing the member of entity it tries to retrieve the data which is not available in database.


Answer: The session.get(Product.class,1) generated SELECT SQL Update SQL will not be generated because the Product is not dirty [ state has not changed, you are setting the same values as present if db] If you are setting different data then dirty checking happens and UPDATE sql will be generated.







ORM with Hibernate