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?
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"?><beansxmlns="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-scanbase-package="br.com.empresa"/><beanid="pooledDataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><propertyname="driverClassName"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql://localhost/banco"/><propertyname="username"value="root"/><propertyname="password"value="123"/></bean><beanid="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"destroy-method="destroy"><propertyname="configurationClass"value="org.hibernate.cfg.AnnotationConfiguration"/><propertyname="dataSource"ref="pooledDataSource"/><propertyname="packagesToScan"value="br.com.projeto.modelo"/><propertyname="hibernateProperties"><props><propkey="hibernate.show_sql">true</prop><propkey="hibernate.format_sql">true</prop><propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><propkey="hibernate.id.new_generator_mappings">true</prop><propkey="hibernate.hbm2ddl.auto">update</prop></props></property></bean><tx:annotation-driven/><beanid="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><propertyname="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
renanjp
Renan valeu companheiro, era ista mesmo a minha dificuldade:
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! ;]
renanreismartins
disponha.
vc ainda pode continuar usando o vraptor e spring sem configurar a session desta maneira.
qq coisa estamos ai
abrasss
renanjp
Simm, o duro é que neste projeto preciso uzar JSF
EHAEHAEHEA
renanjp
Ta, as exceções ja estão mais legiveis agora AHEHHEA
1° dúvida:
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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-scanbase-package="*"/><beanid="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"destroy-method="destroy">//Possofazeristoassim??
<propertyname="configLocation"><value>classpath:/hibernate.cfg.xml</value></property></bean><tx:annotation-driven/><beanid="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><propertyname="sessionFactory"ref="sessionFactory"/></bean></beans>
packagemodel.dao.generic;importjava.io.Serializable;importjava.lang.reflect.ParameterizedType;importjava.util.List;importjavax.persistence.PersistenceContext;importorg.hibernate.Criteria;importorg.hibernate.Query;importorg.hibernate.Session;importorg.hibernate.criterion.Criterion;importorg.hibernate.criterion.Example;importorg.springframework.transaction.annotation.Transactional;/** * * @author renan.paula * * @param <T> entity class */publicclassGenericHibernateDAO<TextendsSerializable>implementsGenericDAO<T>{// Isto esta certo??@PersistenceContextprivateSessionsession;privateClass<T>persistentClass;@SuppressWarnings("unchecked")publicGenericHibernateDAO(){this.persistentClass=(Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];}publicGenericHibernateDAO(Sessionsession,Class<T>persistentClass){this.setSession(session);this.setPersistentClass(persistentClass);}publicvoidsetPersistentClass(Class<T>persistentClass){this.persistentClass=persistentClass;}publicClass<T>getPersistentClass(){if(this.persistentClass==null)thrownewIllegalStateException("PersistentClass has not been set on DAO before usage");returnthis.persistentClass;}publicvoidsetSession(Sessionsession){this.session=session;}publicSessiongetSession(){if(this.session==null)thrownewIllegalStateException("Session has not been set on DAO before usage");returnthis.session;}privateCriteriacreateCriteria(Criterion...criterion){Criteriacriteria=this.getSession().createCriteria(getPersistentClass());for(Criterionc:criterion){criteria.add(c);}returncriteria;}privateQuerycreateQuery(Sessionsession,Stringhql,Object...parans){Queryquery=this.getSession().createQuery(hql);inti=0;for(Objectobject:parans){query.setParameter(i++,object);}returnquery;}@Transactional@Overridepublicvoidsave(Tt){this.getSession().save(t);}@Transactional@Overridepublicvoidupdate(Tt){this.getSession().update(t);this.session.flush();}@Transactional@OverridepublicvoidsaveOrUpdate(Tt){this.getSession().saveOrUpdate(t);}@Transactional@Overridepublicvoiddelete(Tt){this.getSession().delete(t);}@Overridepublicvoidrebind(Tt){this.getSession().refresh(t);}@SuppressWarnings("unchecked")@OverridepublicTfindById(Serializableid){return(T)this.getSession().load(getPersistentClass(),id);}@SuppressWarnings("unchecked")@OverridepublicList<T>findAll(){return(List<T>)this.findByCriteria();}@OverridepublicList<?>findByCriteria(Criterion...criterion){returnthis.createCriteria(criterion).list();}@OverridepublicList<?>findByHQL(Stringhql,Object...parans){returnthis.createQuery(this.session,hql,parans).list();}@OverridepublicObjectfindSingleResultByCriteria(Criterion...criterion){returnthis.createCriteria(criterion).uniqueResult();}@OverridepublicObjectfindSingleResultByHQL(Stringhql,Object...parans){returnthis.createQuery(this.session,hql,parans).uniqueResult();}@SuppressWarnings("unchecked")@OverridepublicList<T>findByExample(TexampleInstance,String...excludeProperty){Criteriacriteria=this.createCriteria();Exampleexample=Example.create(exampleInstance);for(Stringexclude:excludeProperty){example.excludeProperty(exclude);}criteria.add(example);returncriteria.list();}@Overridepublicintcount(){Stringhql=newString("select count(*) from "+getPersistentClass().getSimpleName());returnInteger.parseInt(this.createQuery(this.getSession(),hql).uniqueResult().toString());}}packagemodel.dao.implementations;importmodel.dao.generic.GenericHibernateDAO;importmodel.dao.interfaces.IUserTypeDao;importmodel.entity.UserType;importorg.springframework.stereotype.Repository;@Repository("userTypeDao")publicclassUserTypeDaoextendsGenericHibernateDAO<UserType>implementsIUserTypeDao{@OverridepublicUserTypefindByID(Integerid){returnsuper.findById(id);}@OverridepublicbooleanhaveDescriptionEquals(Stringdescription){Stringhql="SELECT COUNT(*) FROM UserType WHERE description = ?";returnInteger.parseInt(super.findSingleResultByHQL(hql,description).toString())>0;}}
renanreismartins
realmente, component based pra web fede, em especial jsf, porém não vamos começar um flame aqui
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