Spring 3 + Hibernate

Bom dia galera…

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?

Desde já agradeço…
Att :slight_smile:

Seria bem mais facil postar qual o “problema”.Mas de qualquer maneira, a ideia consiste no seguinte:

O spring vai instanciar uma SessionFactory, e a partir dela vc consegue pegar uma sessao corrente e usar normalmente.

Com relação as transações, basta vc informar que bean e metodo devem ser transacionais e ele fara isso através de aspectos.

Prefiro o uso de anotações, mas vc pode fazer com xml tb.

Um exemplo do applicationContext configurando uma sessionFactory e permitindo o uso das anotações:

<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-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/aop
      http://www.springframework.org/schema/aop/spring-aop-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="br.com.empresa" />


	<bean id="pooledDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost/banco" />
		<property name="username" value="root" />
		<property name="password" value="123" />
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" destroy-method="destroy">
		<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
		<property name="dataSource" ref="pooledDataSource" />
		<property name="packagesToScan" value="br.com.projeto.modelo" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.id.new_generator_mappings">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>

	<tx:annotation-driven />

	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>



</beans>

e no seu bean basta anotar a classe (caso queira todos os métodos transacionais) ou o método que deseja com @Transactional

abrasss

Renan valeu companheiro, era ista mesmo a minha dificuldade:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" destroy-method="destroy">  
        <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />  
        <property name="dataSource" ref="pooledDataSource" />  
        <property name="packagesToScan" value="br.com.projeto.modelo" />  
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
                <prop key="hibernate.id.new_generator_mappings">true</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
            </props>  
        </property>  
    </bean>

Com o VRaptor não tive que fazer esta configuração por isso me atrapalhei um pouco, mas hoje mesmo já vejo se consigo fazer isto e dou um FeedBack;

Novamente agradeço…
Abraços! ;]

disponha.

vc ainda pode continuar usando o vraptor e spring sem configurar a session desta maneira.

qq coisa estamos ai

abrasss

Simm, o duro é que neste projeto preciso uzar JSF :frowning:
EHAEHAEHEA

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>

Exception

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;
	}
	
	
}

realmente, component based pra web fede, em especial jsf, porém não vamos começar um flame aqui :smiley:

seguinte man, o problema:

Specified field type [interface org.hibernate.Session] is incompatible with resource type [javax.persistence.EntityManager]

Vc está usando @PersistenceContext em cima de uma Session do Hibernate, não pode.

Ao invés disso, receba uma sessionFactory no seu genericDao

algo como:

public GenericDAOHibernate(SessionFactory factory) {
                session = factory.getCurrentSession();

		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
				.getActualTypeArguments()[0];
	}

assim e retire a anotaçao do seu session

abrassss

Ohoooooooooooooooooo, vlw Renan, hoje já testo…

Tava suspeitando que era isso mesmo, preciso criar vergonha na cara e passar este daoGeneric para JPA
AEAHEHAEHAE

Novamente agradeço!!
Att, :smiley: