Friday, February 14, 2014

Hibernate Basics

Recently, I faced a lot of problem implementing persistence of objects with the database using Hibenate persistence API. If we know exactly, its very easy and straight task implement persistence on the objects with database, otherwise, we might get very peculiar problems where it takes a lot of time to get out of it.

In this article, I will present my experience creating persistence objects using PostgreSql database. I will start from beginning so that you can directly use the source code in your implementation.

1) Get Data Source
Use the following method to get datasource. We use this later when creating properites.
private DataSource getDataSource(String host, String database, String userName, String password) {
PoolProperties poolProps = new PoolProperties();
poolProps.setUrl("jdbc:postgresql://" + host + "/" + database);
poolProps.setDriverClassName("org.postgresql.Driver");
poolProps.setUsername(userName);
poolProps.setPassword(password);

poolProps.setJmxEnabled(true);
poolProps.setTestWhileIdle(false);
poolProps.setTestOnBorrow(true);
poolProps.setValidationQuery("SELECT 1");
poolProps.setTestOnReturn(false);
poolProps.setValidationInterval(30000);
poolProps.setTimeBetweenEvictionRunsMillis(30000);

poolProps.setMaxActive(75);
poolProps.setMaxIdle(25);
poolProps.setInitialSize(3);
poolProps.setMaxWait(10000);
poolProps.setRemoveAbandonedTimeout(60);
poolProps.setMinEvictableIdleTimeMillis(30000);
poolProps.setMinIdle(10);

poolProps.setLogAbandoned(true);
poolProps.setRemoveAbandoned(true);

poolProps.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");

DataSource dataSource = new DataSource();
dataSource.setPoolProperties(poolProps);

return dataSource;
}


2) Create properties object

Properties props = new Properties();
props.put("hibernate.connection.datasource", getDataSource(hostname, database, username, password));
props.put("hibernate.cglib.use_reflection_optimizer", true);
props.put("hibernate.show_sql", false);
props.put("hibernate.hbm2ddl.auto", "update");
props.put("transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
props.put("hibernate.jdbc.batch_size", batchSize);
props.put("hibernate.default_batch_fetch_size", fetchSize);
props.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");


3) Create Configuration

Configuration config = new Configuration();
config.setProperties(props);
//class registration
config.addAnnotatedClass(className);

If we have to register all classes in the specified package, then we have to get all classes inside the package.

4) Create session factory

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(props).buildServiceRegistry();
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);

5) We have to get session for persistent objects, so we get this by:

Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.COMMIT);

6) While executing query

Session session0sessionFactory.openSession();
Transaction trans=session.beginTransaction();
session.delete(object);
trans.commit();
session.close();


Creating persistence objects will remove the bother of thinking the database structure and tables. We just care about objects, and the back end database operations are carried out by hibernate API itself.


No comments:

Post a Comment