Generate the JPA annotated entities from the database tables using hibernate tools

Lets take a look at some graphical step by step procedure to generate java annotated entities from the already available database tables. This can be achieved using Hibernate Tools from JBoss.

Here are some pre-requisites to be taken care of

1. JBOSS Tools eclipse update site
2. Search & Select hibernate tools from the listing
3. Install Hibernate tools
4. Download the hibernate dependencies

Install the Hibernate Tools from the eclipse Install New Software option and go on selecting and accepting the next options:



Lets start by creating a basic JPA project and set it up for magic.

1. Create a new JPA project and add JPA facet configuration

Create e new JPA project 



Select the JPA Facet as Hibernate JPA. Disable JPA configuration


Add a MySQL connection profile and test it for connectivity to your database


Add the MySQL driver and also Select annotated discovery of beans. The final facet page will look like this:



2. Add hibernate dependencies to the build path

Go to the java build path configuration from project properties. Make sure you have downloaded the relevant dependencies and configured it as below.



The final project structure shall look as per the below snapshot




3. I did get a classpath error and I found that I should not be using JPA but core as a Hibernate setting console configuration

Error:  [Classpath]: Could not create JPA based Configuration

Solution: Go to the Hibernate Settings from project properties and select details on your console configurations and set it as per the snapshot here.


4. Generate the entities from the table in your configured database

This is the final step where you generate the java entities by selecting the JPA tools option


Here you have to select the package the generated entities should target along with the console configuration that we already setup before.


As soon as you click Finish here the processing starts and the package should get populated with entities mapped to the tables in the configured database.

We get the generated entity bean here

This is a great help to kickstart your development you wont want to really start writing each annotation and associations manually.

GitHub Link:





Hibernate JPA project to create entities from tables


Hibernate JPA 

Step 1: Install Hibernate tools in your Eclipse JEE IDE

Step 2: Create a JPA Project. JPA Facet should have library configuration disabled and a database connection set as we will add hibernate libraries in the classpath.


Step 3: Add the hibernate JPA libraries in build path



Step 3: Add a connection to the database with tables available

Step 4: In JPA perspective right click the project -> JPA Tools -> Generate entities from table



Migrating from Hibernate-EHCache in-memory resource hell towards optimistic AWS ElastiCache or Memcached

Taking my discussion further away from Hibernate-EHcahe and their terracotta servers.

The in-memory implementation are for the faint hearted. The kind of load we unexpected, brought us to think of a better way. The implementation of hibernate-memcached looks fine but I am not very convinced.

So, what do I do ?  I take it out for a trial run.

Lets migrate the same application to offload the 2nd level cache to the ElastiCache/Memcached provisioned by AWS.

Step 1: Setup a Memcached local instance or Create an Amazon ElastiCache Node in AWS Public Cloud

Note: In AWS be sure to add the ElastiCache server in the same security group as the EC2 instance used for deployment.

Step 2: Update Maven POM

 <!-- Memcache Hibernate integration -->

Step 3: Update the Existing hibernate properties in the session-factory configurations

 <!-- AWS ElasiCache/Memcached Config -->
 <prop key="hibernate.cache.provider_class">com.googlecode.hibernate.memcached.MemcachedCacheProvider</prop>
 <prop key="hibernate.cache.use_query_cache">true</prop>
 <prop key="hibernate.cache.use_second_level_cache">true</prop>
 <prop key="hibernate.memcached.servers"></prop>
 <prop key="hibernate.memcached.cacheTimeSeconds">300</prop>
 <prop key="hibernate.memcached.connectionFactory">DefaultConnectionFactory</prop>
 <prop key="hibernate.memcached.clearSupported">false</prop>

Issues: I still have those Cache annotations with the concurrency configuration which is not good with Memcached as mentioned here. I did get hopeful after an informative read which discussed on deploying hibernate-memcached at an enterprise scale.

Also, the cache timeout are small as i get the object expired exceptions frequently. Need to look into this.

WARN : org.hibernate.cache.ReadWriteCache - An item was expired by the cache while it was locked (increase your cache timeout)

Inference: Still not convinced, as i require more freedom to configure just like Ehcache. The benefits of limiting the memory resources in a pool configuration can not be neglected as I am unsure at this point on the overflow consequences in ElastiCache servers. Ehcache clearly configures as per the specified limit and even accepts percentages for that matter in each domain cache configuration.

However, scalability can be an issue but in terms of 2nd level caching in hibernate we should really be specific  as the data is structured here. Only after analyzing the memory footprint and load we should configure the cache parameters. We can scale mindlessly on objects using memcached on other layers say; static web pages, intermediate results, database internal cache distribution etc. Only if in-memory is really a blocker considering your load, should you move to memcached as ElastiCache service. In this scenario you need to dig into the internals of hibernate-memcached to verify your production usage needs. I am in the process of doing so right now !!!

Spring Hibernate-3 2nd Level EHCache 2.8 Configurations with C3P0 Pooling

Here I am discussing the configurations required to enable a 2nd Level caching using EHCache in a Spring Hibernate 3 ORM setup.

Pre-Requisites: You should have a working hibernate project in order to migrate to EHCache with in-memory and local disk type of caching configuration. Be aware that this implementation uses RAM to maintain the cached collections and should not be handy in case of a large dynamic load. You should move to distributed cache using a Terracotta server arrays or a totally different implementation using the AWS Elastic Cache.

Maven Dependencies:


 <!-- EHCache Dependencies -->


Step 1:  Make sure your hibernate session factory configuration looks like the following,

<bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 <property name="driverClass" value="${jdbc.driverClassName}" />
 <property name="jdbcUrl" value="${jdbc.url}" />
 <property name="user" value="${jdbc.username}" />
 <property name="password" value="${jdbc.password}" />
 <property name="minPoolSize" value="2" />
 <property name="maxPoolSize" value="50" />
 <property name="maxIdleTime" value="319" />
<bean id="mySessionFactory"
 <property name="dataSource" ref="c3p0DataSource" />
 <property name="annotatedClasses">
 <property name="hibernateProperties">
 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
 <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
 <prop key="hibernate.connection.useUnicode">true</prop>
 <prop key="hibernate.connection.characterEncoding">UTF-8</prop>
 <!-- EHCache Configuration -->
 <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
 <prop key="hibernate.cache.use_second_level_cache">true</prop>
 <prop key="hibernate.cache.use_query_cache">true</prop>
 <prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</prop>
 <bean id="transactionManager"
 <property name="sessionFactory" ref="mySessionFactory" />
<context:annotation-config />
<tx:annotation-driven />

From the above config you can be sure that the two domain objects that are being configured with the session factory are using a pooled connection from c3po and have second level cache and query cache enabled. We also observe that the transactions are annotation driven so we dont have to worry about manually doing a begin and commit on any of them.

Step 2: EHCache Configuration file in class path <ehcache.xml>

<ehcache xmlns:xsi=""

 <sizeOfPolicy maxDepth="100000" maxDepthExceededBehavior="abort"/>

 <defaultCache eternal="false" 
    <persistence strategy="localTempSwap"/>

 <cache name="org.hibernate.cache.StandardQueryCache"
    <persistence strategy="localTempSwap"/>

This configuration file is looked up by the cache configuration reader. We have enabled default cache for all the beans and a separate cache for the Queries. Both of these cache will share the resources pooled in the ehcache attributes. Example local heam of 100 MB will be shared equally by all cache.

Step 3: Annotate the Domains with the relevant caching annotation

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "MyTable1")
public class MyBean1 {


Step 4: Make sure you have annotation config in you app context

<context:component-scan base-package=","/>

Step 5: Finally, Make sure your DAO is setting the cache store. This can be set to true in the query creation of session call. Find the relevant examples below.

public Collection<T> getAll() throws DataAccessException {
 return _sessionFactory.getCurrentSession()
public Collection<T> findBySQLQuery(String sqlQueryString)
 throws DataAccessException {
 return _sessionFactory.getCurrentSession()
public Collection<T> findByHSQLQuery(String hsqlQueryString,
 Map<String, Object> map) {
 return _sessionFactory.getCurrentSession().createQuery(hsqlQueryString)
public Collection<T> findByHSQLNamedQuery(String namedQuery,
 Map<String, Object> map) {
 return _sessionFactory.getCurrentSession().getNamedQuery(namedQuery)

This should be helpful in terms of code required to wire up the caching in the project.

Test: A way to test is by switching on the hibernate logging and making a get all query call multiple times. The first time the query should make a sql query connect to the db and respond while the other times it should just return from the local cache without this query to db.

Configure the following in log4j.xml

<category name="org.hibernate" additivity="false">
 <priority value="INFO" />
 <appender-ref ref="console" />