Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Saturday, December 28, 2013

Hibernate Framework flow


The general flow of Hibernate framework while interacting with the Database is:



Example Program:

       // creating the Configuration object       
        Configuration config = new Configuration();
        config.configure();           
       
        // creating the SessionFactory object
        SessionFactory sessionFactory = config.buildSessionFactory();
       
        // creating the Session object
        Session session = sessionFactory.openSession();
        Transaction transaction = null;
        try {
            // creating the Transaction object
            transaction = session.beginTransaction();


           
            Person person = new Person();
            person.setName("Ranga");
 

            // save the Person object
            long personId = (Long) session.save(person);
            session.flush();                   

            // commit the transaction
            transaction.commit();
           
        } catch(HibernateException ex) {
            if(transaction != null) {
                transaction.rollback();
            }
        } finally {
            if(session != null) {
                session.close();
            }
        }             



Step1: Creating the Configuration object
 
First we need to create the Configuration object. After creating Configuration object we need to call configure() method.

Configuration config = new Configuration();
config.configure(); 
  

public Configuration configure() throws HibernateException {
        configure( "/hibernate.cfg.xml" );
        return this;
}

While calling config.configure() method if you are not passing any argument configuration (*.cfg.xml) file then it will take default configuration file called hibernate.cfg.xml file.

This will load all  configuration information like database information, dialect class, mapping files and etc..

Step2: Creating the SessionFactory object

By using configuration object only we can create the SessionFactory.

SessionFactory sessionFactory = config.buildSessionFactory();

Note:   SessionFactory is an interface so directly we can't create the object and SessionFactoryImpl is the implemented class for the SessionFactory.

While calling config.buildSessionFactory() it is internally calls the SessionFactoryImpl class and creates the object that object returns the SessionFactory.

public SessionFactory buildSessionFactory() throws HibernateException {
       // here some more statements    
        return new SessionFactoryImpl(
                this,
                mapping,
                settings,
                getInitializedEventListeners(),
                sessionFactoryObserver
            );
 }

Step3: Creating the Session object

By using SessionFactory object only we can create the Session object.

Session session = sessionFactory.openSession();
 
Session is nothing but get the one physical connection. By using session we can do all CRUD operations.

Note: Like SessionFactory, Session is also an interface and which is implemented by SessionImpl class. In hibernate there are two ways to get the Session object i.e openSession() and getCurrentSession() [ See more info dif b/w openSession() and getCurrentSession()]. In the above statement we are calling sessionFactory.openSession() it gives the Session object.  

public org.hibernate.classic.Session openSession() throws HibernateException {
        // some more statements
       
        return new SessionImpl(
                connection,
                this,
                autoClose,
                timestamp,
                sessionLocalInterceptor == null ? interceptor : sessionLocalInterceptor,
                settings.getDefaultEntityMode(),
                settings.isFlushBeforeCompletionEnabled(),
                settings.isAutoCloseSessionEnabled(),
                settings.getConnectionReleaseMode()
            );
}

Step4: Creating the Transaction object

By using Session object only we can create the Transaction object.

      Transaction transaction = null;
      transaction = session.beginTransaction();

Transaction is a logical unit. While working with insert, update, delete, operations from an hibernate application onto the database then hibernate needs a logical Transaction, if we are selecting an object from the database then we do not require any logical transaction in hibernate.  In order to begin a logical transaction in hibernate then we need to call a method beginTransaction() given by Session Interface.

Note: Transaction is also interface. 

public Transaction beginTransaction() throws HibernateException {
       // some more statements
       Transaction result = getTransaction();
        result.begin();
        return result;
 }

Step5: Now do any CRUD operation

Inside Session interface there are lot of methods is available to do CRUD operations. Some of the important methods is 

Inserting object - save(), saveOrUpdate(), persist()
Selecting object - load(), get(), byId() [ this method is available in hibernate4]
Updating object - update(), saveOrUpdate()
Deleting object - delete()
In the above example i am doing insert operation.

long personId = (Long) session.save(person);

Step6: Commit or rollback the transaction

If the operations is successful then commit() the transaction otherwise rollback() transaction.

transaction.commit();
transaction.rollback();

Step7: Finally close the all resources like session, sessionFactory

So finally close the session
 
session.close();

Exception in thread "main" org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.ranga.pojo.Order. Expected: class java.lang.Long, got class java.lang.Integer


Exception in thread "main" org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.ranga.pojo.Order. Expected: class java.lang.Long, got class java.lang.Integer

Problem: 
While passing primary key value in either load() or get() or byId() the value you passed is integer. but it expecting long value.

Solution: 
You need to pass the long value instead of integer.

org.hibernate.MappingException: Unknown entity:


org.hibernate.MappingException: Unknown entity: com.ranga.mapping.Student

Problem:  
In configuration file you are not added Student class or wrong path.

Solution: 
Add the proper Mapping file in configuration.

org.hibernate.MappingException: Could not determine type for: String, at table: Persons, for columns: [org.hibernate.mapping.Column(FirstName)]

org.hibernate.MappingException: Could not determine type for: String, at table: Persons, for columns: [org.hibernate.mapping.Column(FirstName)]

Problem:  
In Mapping, the type what you specified that the first character will be in Upper case. In the above exception, type will be String.

Solution: 
In hibernate mapping file, use type string instead of String because in hibernate, the type will be case sensitive.

Java type
Mapping type
ANSI SQL Type
int or java.lang.Integer
integer
INTEGER
long or java.lang.Long
long
BIGINT
short or java.lang.Short
short
SMALLINT
float or java.lang.Float
float
FLOAT
double or java.lang.Double
double
DOUBLE
java.math.BigDecimal
big_decimal
NUMERIC
java.lang.String
character
CHAR(1)
java.lang.String
string
VARCHAR
byte or java.lang.Byte
byte
TINYINT
boolean or java.lang.Boolean
boolean
BIT
boolean or java.lang.Boolean
yes/no
CHAR(1) ('Y' or 'N')
boolean or java.lang.Boolean
true/false
CHAR(1) ('T' or 'F')

Exception in thread "main" java.lang.ExceptionInInitializerError

Could not parse mapping document from resource com/ranga/Person.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError

Problem:  
 In Mapping file DTD information is not added or wrong DTD information you are given.

Solution:  
Add the proper DTD information in mapping file(Person.hbm.xml)

java.lang.UnsupportedOperationException: The application must supply JDBC connections.


Exception in thread "main" java.lang.UnsupportedOperationException: The application must supply JDBC connections.

Problem:   
while setting jdbc connection property by using annotation configuration we need to add hibernate in preceed of property.
AnnotationConfiguration config = new AnnotationConfiguration().addAnnotatedClass(User.class);
       config.setProperty("connection.driver_class", "oracle.jdbc.driver.OracleDriver");
       config.setProperty("connection.url", "jdbc:oracle:thin:@localhost:1521:xe");
       config.setProperty("connection.username", "ranga");
       config.setProperty("connection.password", "ranga");

Solution:
AnnotationConfiguration config = new AnnotationConfiguration().addAnnotatedClass(User.class);
       config.setProperty("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver");
       config.setProperty("hibernate.connection.url", "jdbc:oracle:thin:@localhost:1521:xe");
       config.setProperty("hibernate.connection.username", "ranga");
       config.setProperty("hibernate.connection.password", "ranga");  

java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException

Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException

Problem:  
You need to add ehcache*.jar(for example ehcache.2.7.4.jar) file into your classpath.

Solution:  
 Add the ehcache*.jar file to your class path or specify the maven dependency in pom.xml file.

<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache</artifactId>
   <version>2.7.4</version>
</dependency>  

Friday, December 27, 2013

java.lang.NoClassDefFoundError: net/sf/ehcache/util/Timestampe


Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/ehcache/util/Timestamper at org.hibernate.cache.ehcache.internal.regions.EhcacheDataRegion.<init>(EhcacheDataRegion.java:86)    at org.hibernate.cache.ehcache.internal.regions.EhcacheTransactionalDataRegion.<init>(EhcacheTransactionalDataRegion.java:74)   at org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion.<init>(EhcacheEntityRegion.java:58)  at org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory.buildEntityRegion(AbstractEhcacheRegionFactory.java:130)
   at org.hibernate.cache.ehcache.EhCacheRegionFactory.buildEntityRegion(EhCacheRegionFactory.java:48)
   at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:339)
   at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
   at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1775)
   at str.ForOurLogic.main(ForOurLogic.java:15)
Caused by: java.lang.ClassNotFoundException: net.sf.ehcache.util.Timestamper
   at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
   ... 9 more


Problem: I am getting the above exception because of ehcache-core version problem. Here the version number is 2.3.1.

Solution: I migrated to 2.3.1 to 2.4.0


Add the below line in dependency section
<dependency>
           <groupId>net.sf.ehcache</groupId>
           <artifactId>ehcache-core</artifactId>
           <version>2.4.0</version>
       </dependency>

Add below lines to repositories section 
       
       <repository>
           <id>sourceforge-releases</id>
           <name>Sourceforge Releases</name>
           <url>https://oss.sonatype.org/content/repositories/sourceforge-releases</url>
       </repository>