Estou com dificuldades aqui, estou tentando configurar o Spring 3 com o hibernate através do maven, na realidade consegui configura-los mas o problema mesmo esta sendo em fazer o gerenciamento da Session e Transaction pelo spring.
Alguém poderia me dar um exemplo de um arquivo spring-context.xml que tenha o controle da session e transactions?
Ta, as exceções ja estão mais legiveis agora AHEHHEA
1° dúvida:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans. For example @Controller and @Service.
Make sure to set the correct base-package -->
<context:component-scan base-package="*" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" destroy-method="destroy">
// Posso fazer isto assim??
<property name="configLocation">
<value>classpath:/hibernate.cfg.xml</value>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Grave: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userTypeDao' defined in file [C:\Users\Renan JP\Desktop\WorkSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\sourceCode\WEB-INF\classes\model\dao\implementations\UserTypeDao.class]: Post-processing failed of bean type [class model.dao.implementations.UserTypeDao] failed; nested exception is java.lang.IllegalStateException: Specified field type [interface org.hibernate.Session] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:803)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:493)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Specified field type [interface org.hibernate.Session] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.checkResourceType(InjectionMetadata.java:126)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.<init>(PersistenceAnnotationBeanPostProcessor.java:617)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:379)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:320)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:798)
... 22 more
package model.dao.generic;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.PersistenceContext;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author renan.paula
*
* @param <T> entity class
*/
public class GenericHibernateDAO<T extends Serializable> implements GenericDAO<T> {
// Isto esta certo??
@PersistenceContext
private Session session;
private Class<T> persistentClass;
@SuppressWarnings("unchecked")
public GenericHibernateDAO() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public GenericHibernateDAO(Session session, Class<T> persistentClass) {
this.setSession(session);
this.setPersistentClass(persistentClass);
}
public void setPersistentClass(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
public Class<T> getPersistentClass() {
if (this.persistentClass == null)
throw new IllegalStateException("PersistentClass has not been set on DAO before usage");
return this.persistentClass;
}
public void setSession(Session session) {
this.session = session;
}
public Session getSession() {
if (this.session == null)
throw new IllegalStateException("Session has not been set on DAO before usage");
return this.session;
}
private Criteria createCriteria(Criterion... criterion) {
Criteria criteria = this.getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
criteria.add(c);
}
return criteria;
}
private Query createQuery(Session session, String hql, Object... parans) {
Query query = this.getSession().createQuery(hql);
int i = 0;
for (Object object : parans) {
query.setParameter(i++, object);
}
return query;
}
@Transactional @Override
public void save(T t) {
this.getSession().save(t);
}
@Transactional @Override
public void update(T t) {
this.getSession().update(t);
this.session.flush();
}
@Transactional @Override
public void saveOrUpdate(T t) {
this.getSession().saveOrUpdate(t);
}
@Transactional @Override
public void delete(T t) {
this.getSession().delete(t);
}
@Override
public void rebind(T t) {
this.getSession().refresh(t);
}
@SuppressWarnings("unchecked") @Override
public T findById(Serializable id) {
return (T) this.getSession().load(getPersistentClass(), id);
}
@SuppressWarnings("unchecked") @Override
public List<T> findAll() {
return (List<T>) this.findByCriteria();
}
@Override
public List<?> findByCriteria(Criterion... criterion) {
return this.createCriteria(criterion).list();
}
@Override
public List<?> findByHQL(String hql, Object... parans) {
return this.createQuery(this.session, hql, parans).list();
}
@Override
public Object findSingleResultByCriteria(Criterion... criterion) {
return this.createCriteria(criterion).uniqueResult();
}
@Override
public Object findSingleResultByHQL(String hql, Object... parans) {
return this.createQuery(this.session, hql, parans).uniqueResult();
}
@SuppressWarnings("unchecked") @Override
public List<T> findByExample(T exampleInstance, String... excludeProperty) {
Criteria criteria = this.createCriteria();
Example example = Example.create(exampleInstance);
for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
criteria.add(example);
return criteria.list();
}
@Override
public int count() {
String hql = new String("select count(*) from " + getPersistentClass().getSimpleName());
return Integer.parseInt(this.createQuery(this.getSession(), hql).uniqueResult().toString());
}
}
package model.dao.implementations;
import model.dao.generic.GenericHibernateDAO;
import model.dao.interfaces.IUserTypeDao;
import model.entity.UserType;
import org.springframework.stereotype.Repository;
@Repository("userTypeDao")
public class UserTypeDao extends GenericHibernateDAO<UserType> implements
IUserTypeDao {
@Override
public UserType findByID(Integer id) {
return super.findById(id);
}
@Override
public boolean haveDescriptionEquals(String description) {
String hql = "SELECT COUNT(*) FROM UserType WHERE description = ?";
return Integer.parseInt(super.findSingleResultByHQL(hql, description)
.toString()) > 0;
}
}