Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Friday, December 2, 2016

What is MappedSuperClass in hibernate ?

MapperSuperClass


·        A mapped superclass has no separate table defined for it.
·        Designates a class whose mapping information is applied to the entities that inherit from it. 
·        A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself. 
·        When applied to the subclasses the inherited mappings will apply in the context of the subclass tables. 
·        Mapping information may be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations or corresponding XML elements.
·        It avoids the code repetition like adding an id, version or timestamp fields in every Hibernate entity.

Example:

AbstractEntity.java class having MappedSuperClass but no Entity annotation.





User Class extends AbstractEntity class and will persisting user object, it will also persist Id and other details of mapped Class.



You can download the whole source code for Github.

After running the query, Attributes of AbstractEntity class will get created under 'USER' table.


Happy Coding...!!!

Friday, June 26, 2015

org.hibernate.HibernateException: No Session found for current thread

I am working one Spring MVC project in which I have integrated Spring with hibernate and most of the time, I use to get this error message while performing database operation ..

org.hibernate.HibernateException: No Session found for current thread

Reason : This is happening because I have missed declaring the transaction in my Spring Application. sessionFacory needs transaction to work.

Solution :

Define transaction manager in your Spring configuration file. Here is my spring-config.xml file :


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${db.driverClassName}" />
<property name="jdbcUrl"
value="jdbc:mysql://${db.host}:${db.port}/${db.name}" />
<property name="user" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
depends-on="provDB">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="PACKAGE_NAME" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

<bean id="dao" class="DAO_IMPL_CLASS.DaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

and Add @Transactional annotation on your service function

@Override
@Transactional
public String saveConfiguration(...) {
daoImpl.saveConfiguration(configuration);
return "issue_resolved";
}

I guess, It can be useful to many prople.. Happy Coding..!!!

Thursday, October 30, 2014

How to Map a list of strings with JPA/Hibernate annotations ?

Yesterday while working on my project, I got one requirement where I need to store list of Array into the database, I checked on Google, went through various site but didn't get much information. Everyone talks about creating new entity and do onetomany relationship BUT I wanted to create a collection of basic types.

Finally I come across @ElementCollection annotation provided by JPA 2.0 which resolves my problem.

Problem :
Input JSON which we need to store in DB:

{
"schemas": ["urn:scim:schemas:core:1.0", "urn:scim:schemas:extension:enterprise:1.0"]
}
           Where schemas is Array of String.
Solution :


Just add following annotation in your POJO i,e
@ElementCollection
@CollectionTable(name = "SCIM_SCHEMAS", joinColumns = @JoinColumn(name = "SCHEMA_ID"))
@Column(name = "SCIM_SCHEMA")
private List<String> schemas;

It will create the table named "SCIM_SCHEMAS" having columns 'SCHEMA_ID' and 'SCIM_SCHEMA'


For details check section 2.2.5.3.3. Collection of basic types or embeddable objects or feel free to comment :)



Thursday, October 9, 2014

Hibernate Error - Caused by: org.hibernate.DuplicateMappingException: duplicate import:

In hibernate, You cannot have two classes with the same name in the same or different packages else you will get an error at runtime like


"Caused by: org.hibernate.DuplicateMappingException: duplicate import: ....(try using auto-import="false")"


I have resolved this issue by adding property name on the Entity annotation.
Let us suppose I have Meta class in two different packages "com.database.user" and "com.database.group', you can resolve it as :
package com.database.user
@Entity(name= "com.database.user")
@Table(name="USER_META")
public class Meta

package com.database.group
@Entity(name= "com.database.group")
@Table(name="GROUP_META")
public class Meta

There must be some other ways too to resolve this issue, So please feel free to share it :)





Wednesday, April 3, 2013

Hibernate Configuration

To inform Hibernate from where to find mapping information of Java classes to database tables or configuration setting related to database, All such information is usually supplied by Hibernate Configuration Object. It is managed by an instance of org.hibernate.cfg.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 mappings are compiled from various XML mapping files or from Java 5 Annotations.

Hibernate provides following types of configurations
  1. hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH 
  2. hibernate.properties – A Java compliant property file which holds key value pair for different hibernate configuration strings. 
  3. Programmatic configuration – This is the manual approach. The configuration can be defined in Java class. 

1. hibernate.cfg.xml : The hibernate.cfg.xml file is a standard XML file which contains all the configuration parameters like database connection, class mappings etc. This file needs to be placed root of CLASSPATH of application.

Below is the sample hibernate.cfg.xml file :
 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/SampleApp</property>
<property name="connection.username">root</property>
<property name="connection.password">root123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Mapping files POJO -->
<mapping class="com.hibernate.pojo.Host"/>
</session-factory>
</hibernate-configuration>

2. hibernate.properties file :
This is the easiest way to get started with Hibernate. Create a file hibernate.properties and place it in root of your applications CLASSPATH.
 
Below is the sample hibernate.properties file:

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost/SampleApp
hibernate.connection.username=root
hibernate.connection.password=root123
hibernate.connection.pool_size=1
hibernate.dialect = org.hibernate.dialect.MySQLDialect
 3. Programmatic Configuration

We can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:
Configuration cfg = new Configuration()
.addResource("Host.hbm.xml");

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:
Configuration cfg = new Configuration()
.addClass(com.hibernate.pojo.Host.class);

A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:
 Configuration cfg = new Configuration()
.addClass(com.hibernate.pojo.Host.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.connection.datasource", "jdbc:mysql://localhost/SampleApp")
.setProperty("hibernate.order_updates", "true");

Refer here for more details :
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/session-configuration.html#configuration-optional 

Tuesday, April 2, 2013

What is Hibernate ?

What is Hibernate ?
  1. Hibernate is an  open source java based library used to work with relational databases. 
  2. The term Object/Relational Mapping refers to the programming technique for converting data between relational databases and object oriented programming languages such as Java, C# etc.
  3. It is a very powerful ORM solution build on top of JDBC API.
  4. It was initiated by Gavin King in 2001.
  5. It is a persistence framework which is used to store and retrieve data from database. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application
  6. Hibernate  makes use of persistent objects called POJOs (Plain Old Java Objects).
  7. Hibernate maps Java classes(POJO) to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks.
  8. These objects works as a data carrier called DTO (Data Transfer Object). They are used to carry data between different layers.


Hibernate Position

Advantages of Hibernate :

  1. Hibernate takes care of mapping Java classes to database tables using annotation or XML files. You don't need to write any code to map it.
  2.  It provides simple APIs for storing and fetching Java objects directly to and from the database.
  3. If there is change in database or in any table then the only need to change XML file properties. and Java classes which are related to the table.
  4. No need of SQL knowledge, you just need to work on familiar Java data types.
  5. It does not require an application server to operate.
  6.  Reduce database access complexity by easy fetching techniques.
  7. It has easy and simple query for data access.
  8. It is layers architecture and you can use the components as per your application need.
  9. Hibernate is database independent and you can use any database of your choice. It supports all major RDBMS like HSQL Database Engine, DB2/NT, MYSQL, PostgreSQL, FrontBase, Oracle, Microsoft SQL Server, Database,  Sybase SQL Server,  Informix Dynamic Server.
  10. It also provide caching framework that works with Hibernate. You can use any one in your application to improve the performance of your application.

 Hibernate Architecture :

The figure given below represents the architecture of Hibernate :

 

Hibernate framework uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.

Below are some definitions of the object depicts in above diagram :
  • Persistent Object : These are short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one Session. Once the Session is closed, they will be detached and free to be used in any application layer (for example, directly as data transfer objects to and from presentation).
  • Transient Object : Instances of persistent classes those 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.
  • Configuration (org.hibernate.cfg.Configuration ): The configuration of Hibernate is handled by the instance of org.hibernate.cfg.Configuration . It is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.
    Configuration cfg = new Configuration()
  • SessionFactory (org.hibernate.SessionFactory ) : Session factory is a thread safe, immutable cache of compiled mappings for a single database. Configuration object is used to create a SessionFactory object. Only single instance of session factory is required for an application, so it is based on a singleton pattern. Typically SessionFactory is require for per database using a separate configuration file. So in case If you are using multiple databases then you would have to create multiple SessionFactory objects. The SessionFactory is heavyweight object so usually it is loaded at the start of the application.
    SessionFactory sessions = cfg.buildSessionFactory();
  • Session (org.hibernate.Session): The session object provides an interface between the application and data stored in the database. It is a lightweight object and it wraps JDBC connection. It is factory of Transaction, Query and Criteria. It holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.
    Session session = sessions.openSession(); 
  • Transaction (org.hibernate.Transaction): It is a single-threaded, short-lived object used by the application to 
    specify atomic units of work. It is Optional. It provides methods for transaction management.  
  • Query :  Query object use Hibernate Query Language(HQL) or SQL to fetch data from the database. 
  • Criteria : Criteria object are used to create and execute object oriented criteria queries to retrieve objects. 


Wednesday, November 28, 2012

What is Hibernate Caching?

In a typical application, you perform lot of operations like instantiate objects, load object from the database and so on. Sometime in multiuser application you may face a situation in handling multiple call of databases.

Hibernate offers caching functionality which is designed to reduces the amount of necessary database access. This is a very powerful feature if used correctly. It increases your application performance and works between your application and the database as it avoids the number of database hit as many as possible.



Hibernate Cache Types :

Hibernate uses different types of caches. Each type of cache is used for different purposes. Let us first have a look at this cache types.
  • First level cache
  • Second level cache
  • Query level cache

1. First level cache :

First-level cache is the session cache and is always Associates with the Session object. Hibernate uses this cache by default. The Session object keeps an object under its own cache before committing to the database. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

2. Second level cache :

Second-level cache is an optional cache and is always associates with the Session Factory object. The second-level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works.

Hibernate supports four open-source cache implementations named EHCache (Easy Hibernate Cache), OSCache (Open Symphony Cache), Swarm Cache, and JBoss Tree Cache.

Each cache has different performance, memory use, and configuration possibilities.
  
S.N.Cache NameDescription 
1EHCacheIt can cache in memory or on disk and clustered caching and it supports the optional Hibernate query result cache. 
2OSCacheSupports caching to memory and disk in a single JVM, with a rich set of expiration policies and query cache support. 
3warmCacheA cluster cache based on JGroups. It uses clustered invalidation but doesn't support the Hibernate query cache 
4JBoss CacheA fully transactional replicated clustered cache also based on the JGroups multicast library. It supports replication or invalidation, synchronous or asynchronous communication, and optimistic and pessimistic locking. The Hibernate query cache is supported




3. Query level cache :

Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.

Wednesday, August 29, 2012

How to integrate Liquibase with Spring and Hibernate ?

A sample tutorial on how to integrate Liquibase with Spring and Hibernate.

While writing this tutorial, I have added javadoc in the code for better understanding and I believe You already have good knowledge on Spring and Hibernate. The main motto of this tutorial is to give an idea on how you can integrate Liquibase with Spring and Hibernate.

If you are new to Liquibase : Click Here

To integrate liquibase into your project, you need liquibase jars, So download it before starting the project.

I have created an application named "SHLIntegration". The Structure of the project is as follows :

The dependencies are also listed here:

Lets start with Employee class :

1. Create Employee class having getter/setter and add proper JPA annotation to each variable as below.

  public class Employee {

    @Id
    @GeneratedValue
    @Column(name="EMPLOYEE_ID")
    private long id;

    @Column(name="NAME")
    private String name;
   
    @Column(name="GENDER")
    private String gender;
   
    @Column(name="COUNTRY")
    private String country;
   
    @Column(name="ABOUT_YOU")
    private String aboutYou;

.....
....
.... // getter setter of each object

}

2. Create liquibase file i,e db-changelog.xml file

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
       
    <changeSet author="waheed" id="123456789-1">
        <createTable tableName="EMPLOYEE">
            <column autoIncrement="true" name="EMPLOYEE_ID" type="BIGINT">
                <constraints nullable="false" primaryKey="true" />
            </column>
            <column name="NAME" type="VARCHAR(255)" />
            <column name="GENDER" type="VARCHAR(2)" />
            <column name="COUNTRY" type="VARCHAR(255)" />
            <column name="ABOUT_YOU" type="VARCHAR(255)" />
        </createTable>
    </changeSet>
</databaseChangeLog>




3. Add liquibase bean in your bean :

    <bean id="LiquibaseUpdater" class="liquibase.integration.spring.SpringLiquibase">
        <property name="dataSource" ref="dataSource" />
        <property name="changeLog" value="classpath:db-changelog.xml" />
    </bean>


 and others beans which are required for Spring/Hibernate.  Check bean file


The complete tutorial : 
https://github.com/abdulwaheed18/SHLIntegration


Please feel free to do comment or drop me a mail regarding any suggestion/Feedback.
Email : waheedtechblog@gmail.com















 


Friday, August 24, 2012

Error:No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

To solve this problem. You have to do two things:

1. mark the DAO as transactional or function which is doing database call like:

  @Transactional
   public class EmployeeDaoImpl  extends DaoImpl implements EmployeeDao{
 /////
}
           OR
@Transactional
    public long addEmployee(Employee employee) {
        System.out.println("Employee:"+employee );
        long id = employeeDao.addEmployee(employee);
        System.out.println("Id1: " );
        return id;
    }


2. Enable the annotation driven transcation management in applicationContext.xml (where your beans are defined):


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Main transaction manager for accessing internal DB -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
   
    <!-- enable the configuration of transactional behavior based on annotations -->
  <tx:annotation-driven transaction-manager="transactionManager"/>

That's it. Hope it works for other too.

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...