68
HIBERNATE

4794529 Hibernate

Embed Size (px)

DESCRIPTION

Hibernate

Citation preview

  • HIBERNATE

  • INTRODUCTIONWorking with object-oriented software and a relational database is time consumingNeed to bridge relational and object-oriented technologies, or to replace one with the otherHowever the gap between the two is one of the hard facts

    Object-relational mapping tool is required to bridge this gap

  • What is ORM?

    The term Object-Relational Mapping (ORM) refers to the technique of mapping a data representation, from an object model, to a relational data model with SQL-based schema

  • Hibernate OverviewHibernate is a full-featured, open source Object-Relational mapping framework Hibernate is similar to EJB CMP/CMR (container-managed-persistence / container-managed-relationships) and JDO (Java Data Objects)Hibernate focuses entirely on OR mapping for relational databases and includes more features than most commercial productsHibernate helps in developing persistent classes following object-oriented idiom including: association, inheritance, polymorphism, composition, and collectionsHibernate allows to express queries in its own portable SQL extension (HQL)As well as in native SQL, or with an object-oriented Criteria and Example APIHibernate is a Professional Open Source project

  • Hibernate Architecture

  • Hibernate Architecture ExplainedPersistent Objects:Wherein the tables in the Relational Database are represented as Java Classes.

    Hibernate.properties:It contains all configuration parameters required for the application to interact with the database.

    XML Mapping:As the name indicates, links the persistent objects with the underlying database.

  • Hibernate Architectural ApproachesHibernate is flexible and supports several approaches

    Following are the 2 main Architectural approaches in Hibernate:-Lite ArchitectureFull Cream Architecture

  • Hibernate Lite Architecture

  • Hibernate Full Cream Architecture

  • Definition of Hibernate ObjectsSessionFactory (net.sf.hibernate.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.

    Session (net.sf.hibernate.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. Persistent Objects and CollectionsShort-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 (e.g. directly as data transfer objects to and from presentation).

    Transient Objects and CollectionsInstances 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.

  • Definition of Hibernate Objects Transaction (net.sf.hibernate.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. ConnectionProvider (net.sf.hibernate.connection.ConnectionProvider)(Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer. TransactionFactory (net.sf.hibernate.TransactionFactory)(Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.

  • Configuring Hibernate Two types of Configurations:Programmatic ConfigurationXML configuration

    Programmatic ConfigurationAn 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.When all mappings have been parsed by the Configuration, the application must obtain a factory for Session instances. This factory is intended to be shared by all application threads.

  • Programmatic Configuration Sample hibernate.properties file:

    hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriverhibernate.connection.url = jdbc:oracle:thin@localhost:1521:mydatabasehibernate.connection.username = myuserhibernate.connection.password = secrethibernate.dialect = net.sf.hibernate.dialect.Oracle9Dialect

    Programmatically loading of the hibernate.properties:

    Configuration cfg = new Configuration();cfg.getProperties("hibernate.properties");cfg.addResource("Customer.hbm.xml");cfg.setProperty(Environment.SHOW_SQL, "true");SessionFactory sessionFactory = = cfg.buildSessionFactory();

  • XML Configuration An alternative approach to configuration - hibernate.cfg.xml. Used as a replacement for the hibernate.properties file or, if both are present, to override the properties. Configuration file is by default expected to be in the root of the CLASSPATH.

    jdbc:oracle:thin@localhost:1521:mydatabasemyuseroracle.jdbc.driver.OracleDrivernet.sf.hibernate.dialect.Oracle9Dialectsecret true

  • XML Configuration Loading of the XML configuration

    Configuration cfg = new Configuration();cfg.configure("hibernate.cfg.xml");SessionFactory sessionFactory = = cfg.buildSessionFactory();

  • Creating Persistent Classes Persistent classes are classes in an application 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 the persistent classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model. All persistent classes must have a default constructor (which may be non-public) so Hibernate can instantiate them using Constructor.newInstance(). So, most POJOs are Hibernate-compatible without any changes.

  • Hibernate Basic O/R Mapping Elements Hibernate Mapping is an xml file which provides the complete mapping from the persistence class to the table it represents. The elements in xml:-

  • Hibernate O/R Mapping Root Element Hibernate Mapping is the root element enclosing the other elements. A few attributes include:-

  • Basic O/R Mapping Element The element is used to map the class name to the table name. The element with the attributes are as follows:-

  • Basic O/R Mapping Elements This tag is used to map the primary key of the table to an instance variable of the class.
  • Basic O/R Mapping - element The optional element names a java class used to generate unique identifiers (or primary keys) for instances of the persistent class. Few built-in generators include:-increment : generates unique identifiers when no other process is inserting data in the same table.sequence : uses the named sequence to generate the unique primary key.hilo : A table and column is specified in this case. The column specifies the next unique value for the key.seqhilo : A table, column and sequence name is specified. The next unique value is generated using the sequence on the specific column value.

  • Basic O/R Mapping element This tag is used to map the other attributes of the table with the instance variables of the class.

    Formula attribute is an SQL expression that defines the value for a computed property. That is a property which doesnt have a column of their own.

  • Hibernate Basic O/R Mapping Hibernate Type : Hibernate types are used to map the Java property type to a JDBC type. For instance the java.lang.String in Java is varchar in JDBC. The hibernate type for this is string.Mapping type Java typeStandard SQL built-in typeinteger int or java.lang.Integer INTEGERlong long or java.lang.Long BIGINTshort short or java.lang.Short SMALLINTfloat float or java.lang.Float FLOATdouble double or java.lang.Double DOUBLEbig_decimal java.math.BigDecimal NUMERICcharacter java.lang.String CHAR(1)string java.lang.String VARCHARbyte byte or java.lang.Byte TINYINTboolean boolean or java.lang.Boolean BITyes_no boolean or java.lang.Boolean CHAR(1) ('Y' or 'N')true_false boolean or java.lang.Boolean CHAR(1) ('T' or 'F')

  • Hibernate Basic O/R Mapping

  • Hibernate Basic O/R Mapping Elements If the composite keys of a table has to be mapped, the tag can be used.Format:-

    The tag specifies the set of columns which makes the composite key.

  • Retrieving/Storing Java Object Retrieving Data:Session session = sessionFactory.getSession();Customer customerObj = (Customer) session.load(Customer.class, new Long(id));orCustomer customerObj = (Customer) session.get(Customer.class, new Long(id));

    Storing Data:Customer customerObj = new Customer();customerObj.setCustomerId(id);customerObj.setBirthDate(date);customerObj.setName(Shiv);Session session = sessionFactory.getSession();Transaction transaction = session.beginTansaction();session.save(customerObj);transaction.commit();

  • Hibernate Collection Mapping A collection represents a group of objects, known as its elements. Collections in classes can also be mapped using hibernate and this is done using Collection mapping. The elements used are based on the interface used in the class. Like:-SetListMapThere can be a collection of values or entitiesFor values, tag is usedFor entities, or tag Is used

  • Hibernate Collection Mapping - Set A Set can be thought of as any collection of distinct objects considered as a whole.

    Consider the two tables lecturer and StudentLecturerStudent

    Lect_idLect_subj

    Stud_idStud_nameLect_id

  • Hibernate Collection Mapping - Set Consider the case where 1 lecturer has many students:-The following set tag is written in the hibernate mapping file of the Lecturer tag.

    The tag here represents the column in the Lecturer class which is a foreign key for the Student class. i.e. the key with which the two classes are linked.

    The tag specifies the class with which the mapping is to be done and the foreign key column in the class.

  • Hibernate Collection Mapping - Map A map is a simple name-value pair. They have a unique id. ...

    Car_idCar_Name

    Car_idProp_nameProp_value

    Car

    Car_prop

  • Hibernate Collection Mapping - ListList is an ordered collection of entities. Consider the above tables.

  • Hibernate Association Mapping one-to-one association

    SQL Scripts

    create table parent ( id bigint not null primary key )

    create table child ( id bigint not null primary key, name varchar(255), parent_id bigint )

    alter table child add constraint childfk0 (parent_id) references parent

    If the scenario is: one parent-one child

  • Hibernate Association Mapping one-to-many association

    SQL Scripts

    create table parent ( id bigint not null primary key )

    create table child ( id bigint not null primary key, name varchar(255), parent_id bigint )

    alter table child add constraint childfk0 (parent_id) references parent

  • Hibernate Association Mapping many-to-one association

    SQL Scripts

    create table parent ( id bigint not null primary key )

    create table child ( id bigint not null primary key, name varchar(255), parent_id bigint not null)

    alter table child add constraint childfk0 (parent_id) references parent

  • Hibernate Association Mapping many-to-many association

    SQL Scripts

    create table parent ( id bigint not null primary key )

    create table child ( id bigint not null primary key, name varchar(255) )

    create table childset ( parent_id bigint not null, child_id bigint not null, primary key ( parent_id, child_id ) )

    alter table childset add constraint childsetfk0 (parent_id) references parent

    alter table childset add constraint childsetfk1(child_id) references child

  • Hibernate Association Mapping Saving/Retrieving Data:

    Parent parentObj = new Parent();Child childObj = new Child();....Set children = new HashSet();children.add(childObj);parentObj.setChildren(children);session.save(parentObj);children = parentObj.getChildren();

  • Hibernate Component MappingMapping a dependant object using Component Mapping:

    Note: The person table would have the columns pid, birthday, initial, first and last.

  • Hibernate Component MappingMapping a collection of dependant objects using Component Mapping:

  • Hibernate Component Mapping Components as Map IndicesThe element lets you map a component class as the key of a Map Components as Composite Identifiers

    ....

  • Hibernate Inheritance Mapping Inheritance is the process that allows a class to acquire the properties of another class.

    This can be mapped in hibernate using Inheritance mapping.

    There are three basic inheritance mapping strategies:-

    Table per class hierarchyTable per subclassTable per concrete class

  • Hibernate Inheritance MappingTable per Class hierarchy:

    Table per class strategy maps the whole class hierarchy into one table, and classes are differentiated by a discriminator column.

    ............

  • Hibernate Inheritance MappingThe Table per class strategy uses a element which specifies the column based on which the subclasses are differentiated.

    The element used to identify each subclass is:-

    This element has an attribute discriminator-value, which specifies the value of the discriminator column for this subclass.The tags within each specifies the properties which are of the subclass.

    For instance, consider the above example. The subclass CredtCardPayment has a discriminator-value as CREDIT which signifies that the rows in the table PAYMENT having the PAYMENT_TYPE value as CREDIT belongs to this subclass.

    The property creditCardType specifies the attribute of the CreditCardPayment subclass.

  • Hibernate Inheritance MappingTable per subclass:Table per subclass strategy maps the base class into one table, and additional attributes in subclasses are mapped to additional tables joined back to the base table with foreign keys.

    ............

  • Hibernate Inheritance MappingIn this strategy, all the attributes of the parent class are present in 1 table and the attributes specific to the subclasses are present in individual tables.

    The mapping is done by using element. The subclasses are joined by a foreign key.

    The table attribute of the element signifies the table to which these subclasses are mapped. And the key tag specifies the foreign key of the subclass.

    For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the foreign key which joins the subclasses to the parent class. The tag specifies the attributes of the respective tables.

  • Hibernate Inheritance MappingTable per concrete class: In this strategy, each concrete class gets its own table, and all the inherited attributes are mapped to that table as well. The primary keys have to be shared between the tables.

    ............

  • Hibernate Inheritance MappingIn this strategy, all the concrete classes have a table of its own.

    The mapping is done by using element. All the subclasses have a common primary key.

    The table attribute of the element signifies the table to which these subclasses are mapped.

    For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the primary key of all the subclasses. The tag specifies the attributes of the respective tables.

  • Hibernate Query LanguageHibernate is equipped with a powerful query language of its own (HQL) to access Database. HQL is used for building queries to find or filter data from DB.HQL is object oriented version of SQL.HQL supports transparent and relational persistence.HQL queries are database independent.HQL supports advanced features like pagination, fetch joining with dynamic profiling, inner, outer and full joining.HQL also supports usage of aggregate functions, ordering, grouping, sub queries and SQL function callsMost keywords in SQL are optional in HQLHQL is case sensitive.

  • Hibernate Query LanguageSimplest Possible HQL query :-

    from Employee Returns all Employee rows from data base in the form of Employee class objects which is mapped to the table Employee

    HQL is polymorphic which returns instances of all sub classes of a class

    Clauses :- Select (Optional) from (Required except with Session and Filter) where ( Optional) Other : Order By, Group By, Having

  • Writing Simple HQL Before writing the query we have to obtain an instance of hibernate session which is already opened at the start of the application while loading the configuration files.

    org.hibernate.Session defines the Session interface to hold the current session.

    Session session = HibernateSessionFactory.currentSession();

    Now the session variable has an instance of the current session

  • Writing Simple HQL where clauseInterface org.hibernate.Query defines Query interface to hold the query written on the session

    Query query = session.createQuery(from Employee); List queryList = query.list(); Now the queryList contains list of objects returned by the query.

    where clause allows to narrow the list of instances returned. For example:

    from Employee where Employee.id = :empId

    returns All Employee with id as empId.

  • Writing Simple HQL select clause select clause picks the objects and properties to return in the query result set.

    select id from Employee

    This query will return the id of all Employee

    select id from Employee where Employee.salary :> 10000

    This query returns the id of all Employee with salary greater than 10000

  • Writing Simple HQL Polymorphic queries HQL queries are polymorphic due to inheritance mapping.

    from Employee Will return the instances not only of Employee but also all the subclasses of Employee.

    HQL polymorphic queries will return instances of all the persistence classes that extend the class or implement the interface.

  • HQL Complex QueriesHQL supports sub queries and co related sub queries if underlying data base supports it.

    HQL supports all joining queries along with fetch joining.

    HQL allows handling of data with visibility rules using Hibernate Filters.

    Narrowing of Result Objects returned can be done by using Criteria Queries.

    Native SQL queries can be used to write queries in SQL format, retaining the benefits of transparent persistence.

    Named HQL queries can be created for reusability.

  • Criteria QueriesHQL has criteria queries to perform operations like narrowing the result set object which are returned based on the criteria defined at runtime.

    Interface org.hibernate.Criteria represents query against a particular class.

    Session is a factory for Criteria instances.

    Criteria crit = session.createCriteria(Employee.class);crit.setMaxResults(50); List cats = crit.list();

    Required criteria can be given to the Criteria instance (crit)

  • Criteria Queries Narrowing the result set List cats = sess.createCriteria(Cat.class) .add( Expression.like("name", "Fritz%") ) .add( Expression.between("weight", minWeight, maxWeight) ) .list();

    List cats = sess.createCriteria(Cat.class) .add( Expression.like("name", "Fritz%") ) .add( Expression.or( Expression.eq( "age", new Integer(0) ), Expression.isNull("age") ) ) .list();

  • Example QueriesExample example = Example.create(cat) .excludeZeroes() //exclude zero valued properties .excludeProperty("color") //exclude the property named "color" .ignoreCase() //perform case insensitive string comparisons .enableLike(); //use like for string comparisons

    List results = session.createCriteria(Cat.class) .add(example) .list();

  • Native SQLHibernate allows developers to write complex queries in the SQL format itself using native SQL interface, retaining the advantages of persistence.

    Query sqlQuery = sess.createSQLQuery("select {cat.*} from cats {cat}", "cat", Cat.class);sqlQuery.setMaxResults(50);List cats = sqlQuery.list();

    List queryList = session.createSQLQuery(select * from Employee).addEntity(Employee.class).list();

    addEntity() will do the necessary mapping of Employee table to Employee class which results in returning generic objects.

  • Native SQL String sql = "select cat.originalId as {cat.id}, " + " cat.mateid as {cat.mate}, cat.sex as {cat.sex}, + " cat.weight*10 as {cat.weight}, cat.name as {cat.name}" + " from cat_log cat where {cat.mate} = :catId"

    List loggedCats = sess.createSQLQuery(sql, "cat", Cat.class) .setLong("catId", catId) .list();

  • Named SQL QueryNamed SQL queries can be defined in the mapping document and can be called in the application by query name which allows reusing of queries

    List people = sess.getNamedQuery("mySqlQuery") .setMaxResults(50) .list();

    The named SQL query is in the mapping file

    Select person from Employee

  • Hibernate FiltersHibernate filter is a global named parameterized filter that may be enabled or disabled for a particular hibernate session.

    In order to use filters they must be defined and attached to appropriate mapping elements. To define a filter use element within element. Filters can be enabled or disabled at session level.

  • Hibernate Filters Narrowing the result setDefining Filter :

    Attaching the filter to a class:

    Enabling or Disabling Filters:

    By default Filters are disabled. They have to be enabled on session level to use.

    session.enableFilter(myFilter)

    Will enable the filter myFilter for the Session session.

  • Hibernate Session Management / Thread-safe Session objectimport org.hibernate.*;import org.hibernate.cfg.*;

    public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static { try { // Create the SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // Open a new Session, if this Thread has none yet if (s == null) { s = sessionFactory.openSession(); session.set(s); } return s; }

    public static void closeSession() throws HibernateException { Session s = (Session) session.get(); session.set(null); if (s != null) s.close(); }}

  • Object States

  • Transactions and ConcurrencyYou should observe the following practices when creating Hibernate Sessions:Never create more than one concurrent Session or Transaction instance per database connection.Be extremely careful when creating more than one Session per database per transaction. The Session itself keeps track of updates made to loaded objects, so a different Session might see stale data.The Session is not threadsafe! Never access the same Session in two concurrent threads. A Session is usually only a single unit-of-work!

  • Transactions and ConcurrencyLong session with automatic versioningA single Session instance and its persistent instances are used for the whole application transaction.Many sessions with automatic versioningEach interaction with the persistent store occurs in a new Session.Application version checkingEach interaction with the database occurs in a new Session that reloads all persistent instances from the database before manipulating them.This approach forces the application to carry out its own version checking to ensure application transaction isolation.

  • Hibernate Performance TuningLists, maps and sets are the most efficient collections to updateOne shot deleteUsing Proxy for Lazy LoadingUsing batch fetchingCache Mapping

  • ReferencesWebsites:http://www.hibernate.orghttp://hibernate.bluemars.net/hib_docs/reference/en/html/index.htmlBooks:Hibernate Reference Document Version: 3.0.5Hibernate in Action - By Christian Bauer and Galvin King

  • HappyO/R Mapping withHibernate!