Showing posts with label orm. Show all posts
Showing posts with label orm. Show all posts

Thursday, July 7, 2011

Pre-requisites for hibernate

We need following tools and binaries:

1.The IDE used is Eclipse Indigo(latest one while writing this post).
2.Hibernate binaries(Hibernate Core 3.6.5 final) can be downloaded from here
3.Database HSQLDB 1.9 or H2 database or any other database

The next step is unzip Hibernate Tools 3.2.4 GA and put features and plugins contents to features and plugins directory of Eclipse Galileo. Ensure you have closed Eclipse IDE prior to this step and once you are done with copying part then restart the Eclipse Galileo.


You have to ensure following JARs have been included in the project:

-hibernate3.jar(contains all core Hibernate files)
-antlr
-commons-collections
-dom4j
-javassist
-jta
-slf4j
-slf4j-simple-1.5.8.jar(download it from here)
-hsqldb.jar(used for connecting to HSQL Database) or h2.jar (already present in bin folder of h2 downloaded zip)

Saturday, June 25, 2011

What is ORM?

ORM stands for Object-Relational Mapper. It’s mostly used to define a relationship between an object/class and the database table where it’s data should be saved.
Basic idea of Object Relational Mapping(ORM) is converting data between incompatible types in oop languages.When it comes to data bases it is about creating creating virtual data base objects which can be used in object oriented programming.
See the diagram:


Above diagram clearly explains the task of ORM mapping. To get the overall task done first we need to select a good data base driver which create the connection between our program and the data base. this method is efficient than manually create data base connection every where and close the connection.

Friday, June 24, 2011

Why should you use Hibernate?

There are couple of reasons to use hibernate:
Reason 1 - Performance

Hibernate generates very efficient queries very consistently. However, that is only the begining of the performance story. Hibernate employs very agressive, and very intelligent first and second level caching strategy. This is a major factor in acheiving the high scalability.
Hibernate spares you a unnecessary database calls. So all these lookup tables, and rarely changing data can get cached, and much more.
It allows you to cache how much you want, and it can be very intelligent with write-backs. Furthermore, it integrates well with the major open source (OSCache, EHCache, JBossCache, ...) and commercial caching products such as Tangosol giving you an opportunity to use even more sophisticated features that come with these products.

Reason 2 - Effective Cross-Database Portability

Hibernates portability accross the relational databases is amazing.
It is literally one configuration paramter change. You only have to change the database dialect. This property was especially helpful in my previous company because we used to deploy to wide range of databases since had bunch of extra licenses, so we never knew if the DBA manager would allocate us a Sybase or DB2. So we used to develop on MySQL, and then deploy on whatever. The only change was the change of the dialect - one line change in the configuration file.
That was it!

Reason 3 - Developers' Productivity

I have to admit that Hibernate ,like other sophisticated frameworks, has a steep, but short learning curve, but once you got it - you got it. It becomes a breeze to work with, and it feels like a magic.

But who shouldn't use hibernate?
If your project is using lots of stored procedures, please don't use Hibernate.

Fetching strategies in hibernate

join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
Hibernate also distinguishes between:
Immediate fetching - an association, collection or attribute is fetched immediately, when the owner is loaded.
Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
"Extra-lazy" collection fetching - individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)
Proxy fetching - a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.
"No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.
Lazy attribute fetching - an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.
We use fetch to tune performance. We may use lazy to define a contract for what data is always available in any detached instance of a particular class.

[Source:Hibernate Reference Documentation]

What are core interfaces for Hibernate framework?

Most Hibernate-related application code primarily interacts with four interfaces provided by Hibernate Core:
org.hibernate.Session
org.hibernate.SessionFactory
org.hibernate.Criteria
org.hibernate.Query

The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not thread safe.

The application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. If the application accesses multiple databases, it needs one per database.

The Criteria provides a provision for conditional search over the resultset.One can retrieve entities by composing Criterion objects. The Session is a factory for Criteria.Criterion instances are usually obtained via the factory methods on Restrictions.
Query represents object oriented representation of a Hibernate query. A Query instance is obtained by calling Session.createQuery().

More Hibernate Questions

Question: What are common mechanisms of configuring Hibernate?
Answer: 1. By placing hibernate.properties file in the classpath.
2. Including elements in hibernate.cfg.xml in the classpath.

Question:How can you create a primary key using Hibernate?
Answer: The 'id' tag in .hbm file corresponds to primary key of the table:
Here Id ="empid", that will act as primary key of the table "EMPLOYEE".

Question: In how many ways one can map files to be configured in Hibernate?
Answer: 1. Either mapping files are added to configuration in the application code or,
2.hibernate.cfg.xml can be used for configuring in .

Question: How to set Hibernate to log all generated SQL to the console?
Answer: By setting the hibernate.show_sql property to true.

Question: What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?
Answer: The settings of the XML configuration file will override the settings used in the properties.

Question: What methods must the persistent classes implement in Hibernate?
Answer: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it requires a constructor with no arguments for every persistent class. And getter and setter methods for all the instance variables.

Question: How can Hibernate be configured to access an instance variable directly and not through a setter method?
Answer: By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

Question: How to declare mappings for multiple classes in one mapping file?
Answer:Use multiple elements. But, the recommended practice is to use one mapping file per persistent class.

Question: How are the individual properties mapped to different table columns?
Answer: By using multiple elements inside the element.

Question: What are derived properties?
Answer: The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

Question: How can you make a property be read from the database but not modified in anyway (make it immutable)?
Answer: Use insert="false" and update="false" attributes.

Question: How can a whole class be mapped as immutable?
Answer: By using the mutable="false" attribute in the class mapping.

Friday, June 17, 2011

How to setup H2 database for database connections in java?

Download H2 database
Download H2 database from - H2 download, I downloaded the platform independent version. Extract the zip to some directory.
Run the H2 engine
Now migrate to bin extracted folder, and go to bin folder. Double click on h2.bat and the database engine starts.
Add the jars 
Add H2 jar present in the same bin folder to the java project and add following class to the project and run it.

Now test the code:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class H2Test
{
  public static void main( String args[] ) throws Exception
  {
    Class.forName( "org.h2.Driver" );
    Connection conn = null;
    Statement stmt = null;

    try
    {
      conn = DriverManager.getConnection( "jdbc:h2:file:db/test", "sa", "" );
      stmt = conn.createStatement();
      stmt.executeUpdate( "create table person(name varchar(10));" );
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
    finally
    {
      if( stmt != null )
      {
        try
        {
          stmt.close();
          System.out.println("Test done");
        }
        catch( Exception e )
        {
          e.printStackTrace();
        }
      }

      if( conn != null )
      {
        conn.close();
      }

    }

  }
}


Wednesday, June 15, 2011

Hibernate generator classes

In Hibernate the optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class.

If any parameters are required to configure or initialize the generator instance, they are passed using the <param>element.

<id name="id" type="long" column="cat_id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
<param name="column">next_hi_value_column</param>
</generator>
</id>



All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface; some applications may choose to provide their own specialized implementations. However, Hibernate provides a range of built-in implementations. There are shortcut names for the built-in generators:


increment

generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

guid

uses a database-generated GUID string on MS SQL Server and MySQL.

native

picks identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.

select

retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

sequence-identity

a specialized sequence generation strategy which utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to actually return the generated identifier value as part of the insert statement execution. This strategy is only known to be supported on Oracle 10g drivers targetted for JDK 1.4. Note comments on these insert statements are disabled due to a bug in the Oracle drivers.



    Reference




    Extracted from Hibernate online official tutorials



    List of Cache Provider in Hibernate and their concurrency support details


    Here in this port you can find the list of Cache providers and their Concurrency support details. (Exerted from Official Hibernate Tutorial)
    EHCache (Easy Hibernate Cache)
    (org.hibernate.cache.EhCacheProvider)
    • It is fast.
    • lightweight.
    • Easy-to-use.
    • Supports read-only and read/write caching.
    • Supports memory-based and disk-based caching.
    • Does not support clustering.
    OSCache (Open Symphony Cache)
    (org.hibernate.cache.OSCacheProvider)
    • It is a powerful .
    • flexible package
    • supports read-only and read/write caching.
    • Supports memory- based and disk-based caching.
    • Provides basic support for clustering via either JavaGroups or JMS.
    SwarmCache (org.hibernate.cache.SwarmCacheProvider)
    • is a cluster-based caching.
    • supports read-only or nonstrict read/write caching .
    • appropriate for applications those have more read operations than write operations.
    JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)
    • is a powerful replicated and transactional cache.
    • useful when we need a true transaction-capable caching architecture .
    Cache providers.
    Cache
    Provider class
    Type
    Cluster Safe
    Query Cache Supported
    Hashtable (not intended for production use)
    org.hibernate.cache.
    HashtableCache
    Provider
    memory
    yes
    EHCache
    org.hibernate.cache.
    EhCacheProvider
    memory, disk
    yes
    OSCache
    org.hibernate.cache.
    OSCacheProvider
    memory, disk
    yes
    SwarmCache
    org.hibernate.cache.
    SwarmCacheProvider
    clustered (ip multicast)
    yes (clustered invalidation)
    yes (clock sync req.)
    JBoss Cache 1.x
    org.hibernate.cache.
    TreeCacheProvider
    clustered (ip multicast), transactional
    yes (replication)
    yes (clock sync req.)
    JBoss Cache 2
    org.hibernate.cache.
    jbc2.JBossCache
    RegionFactory
    clustered (ip multicast), transactional
    yes (replication or invalidation)
    yes (clock sync req.)
    Cache Concurrency Strategy Support
    Cache
    read-only
    nonstrict-read-write
    read-write
    transactional
    Hashtable (not intended for production use)
    yes
    yes
    yes
    EHCache
    yes
    yes
    yes
    OSCache
    yes
    yes
    yes
    SwarmCache
    yes
    yes
    JBoss Cache 1.x
    yes
    yes
    JBoss Cache 2
    yes
    yes

    Chitika