Quiero saber ¿Cómo cerrar la sesión hibernate, si estoy manejando la transacción con Spring 4.x?.
Modelo
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="EGRESOS")
public class Egreso {
@Id
@GeneratedValue
@Column(name="id")
private Long id;
@Temporal (TemporalType.DATE)
@Column(name="fecha")
private Date fecha;
@Column(name="importe")
private Double importe;
@Column(name="detalle")
private String detalle;
public Egreso() {
// TODO Auto-generated constructor stub
}
//all getters and setters
Persistencia
public abstract class CustomHibernateSupport<T> extends HibernateDaoSupport implements IGenericDAO<T> {
private Class<T> persistentClass;
@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings({ "unchecked", "deprecation" })
public CustomHibernateSupport() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
this.sessionFactory = new Configuration().configure() // configures
// settings from
// hibernate.cfg.xml
.buildSessionFactory();
}
@PostConstruct
public void init(){
setSessionFactory(sessionFactory);
getHibernateTemplate().setCacheQueries(true);
}
public Class<T> getPersistentClass() {
return persistentClass;
}
public void setPersistentClass(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
public void insert(T entity) {
getHibernateTemplate().save(entity);
}
public void delete(T entity) {
getHibernateTemplate().delete(entity);
}
public void update(T entity){
getHibernateTemplate().update(entity);
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
Session session = getSessionFactory().openSession();
Criteria cr = session.createCriteria(getPersistentClass());
return cr.list();
}
@SuppressWarnings("unchecked")
public T findById(Long id) {
Session session = getSessionFactory().openSession();
Criteria criteria= session.createCriteria(getPersistentClass());
criteria.add(Restrictions.eq("id",id));
return (T) criteria.uniqueResult();
}
@SuppressWarnings("unchecked")
public List<T> findByDate(Date date) {
System.out.println(date);
Session session = getSessionFactory().openSession();
Criteria criteria= session.createCriteria(getPersistentClass());
criteria.add(Restrictions.eq("fecha",date));
return criteria.list();
}
}
Servicio
@Transactional(readOnly=false)
public boolean cargarGasto(GastosRequestDTO nuevo){
Egreso e = new Egreso();
try{
e.setDetalle(nuevo.getDetalle());
e.setFecha(nuevo.getFecha());
e.setImporte(nuevo.getImporte());
egreso.insert(e);
log.info("se inserto correctamente el nuevo gasto ID: "+ e.getId());
return true;
}
catch(Exception ex){
log.error(Throwables.getStackTraceAsString(ex));
log.error("No se pudo insertar gasto ");
}
return false;
}
Controlador
public void cargarGasto() {
GastosRequestDTO nuevoGasto = new GastosRequestDTO();
nuevoGasto.setFecha(fecha);
nuevoGasto.setDetalle(descripcion);
nuevoGasto.setImporte(importe);
if (hotel.cargarGastos(nuevoGasto)) {
obtenerBalance();
setImporte(null);
setDescripcion(null);
}
}
ApplicattionContex.xml
<context:annotation-config/>
<context:component-scan base-package="ar.com.as.hotel"/>
<bean id="recordDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
lazy-init="true" destroy-method="close">
<property name="driverClass" value="org.gjt.mm.mysql.Driver" />
<!-- CHANGE THE DATABASE CONNECTION-->
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/hotelTest"/>
<property name="user" value="********" />
<property name="password" value="********" />
<!-- ***************************************** -->
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="100" />
<property name="initialPoolSize" value="5" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation">
<value>./WEB-INF/classes/hibernate.cfg.xml</value>
</property>
<property name="dataSource">
<ref bean="recordDataSource" />
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
Hibernate.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hotel***</property>
<property name="connection.username">******</property>
<property name="connection.password">******</property>
<property name="hbm2ddl.auto">update</property>
<property name="connection.autocommit">false</property>
<!-- <mapping resource="Cliente.hbm.xml" /> -->
<mapping class="ar.com.as.hotel.modelo.Ingreso" ></mapping>
<mapping class="ar.com.as.hotel.modelo.Precio"></mapping>
<mapping class="ar.com.as.hotel.modelo.Habitacion"></mapping>
<mapping class="ar.com.as.hotel.modelo.Temporada"></mapping>
<mapping class="ar.com.as.hotel.modelo.Egreso"></mapping>
<!-- List of XML mapping files -->
</session-factory>
</hibernate-configuration>