Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic DAO layer and configuration of Transaction Manager, SessionFactory in Hibernate for PostgreSQL
package com.bytestree.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
@SuppressWarnings("unchecked")
public abstract class AbstractDao<E> implements EntityDao<E> {
private final Class<E> entityClass;
public AbstractDao() {
this.entityClass = (Class<E>) ((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
@Autowired
private SessionFactory sessionFactory;
protected Session getSession() {
return this.sessionFactory.getCurrentSession();
}
@Override
public E findById(final Serializable id) {
return (E) getSession().get(entityClass, id);
}
@Override
public void save(E entity) {
getSession().saveOrUpdate(entity);
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.showsql}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.batch.size}</prop>
</props>
</property>
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.bytestree.model</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${datasource.driver}" />
<property name="url" value="${datasource.url}" />
<property name="username" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
</bean>
</beans>
package com.bytestree.dao;
import org.springframework.stereotype.Repository;
import com.bytestree.model.Users;
@Repository("userDao")
public class UserDaoImpl extends AbstractDao<Users> implements UserDao {
}
@bytestree

This comment has been minimized.

Copy link
Owner Author

bytestree commented May 6, 2016

Refer Spring Security 4 with Hibernate for complete example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.