Vraptor 3 + Hibernate 4 -> SessionCreator não carrega [RESOLVIDO]

8 respostas
macspace

Olá pessoal, estou começando agora com o Vraptor3, e criei a seguinte estrutura de pacotes:

recap
 -> controller.auxiliar
 -> dao.auxiliar
 -> model.auxiliar

seguindo os tutoriais e posts do fórum, eu criei o seguinte BEAN:

@Entity
@Table(name="cidade")
@SequenceGenerator(name = "seqCidade", sequenceName = "seq_cidade")
public class CidadeBean {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO, generator = "seqCidade")
	@Column(name="id")
	private Integer id;
	
	@Column(name="cid_descricao")
	private String descricao;

	@Column(name="cid_estado")
	private String estado;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getDescricao() {
		return descricao;
	}

	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}

	public String getEstado() {
		return estado;
	}

	public void setEstado(String estado) {
		this.estado = estado;
	}
}

Fiz o meu DAO da seguinte forma:

@Component
public class CidadeDao {

	private Session session;
	
	public CidadeDao(Session session) {
		this.session = session;
	}
	
	public void adiciona(CidadeBean cidade) {
		session.save(cidade);
	}
	
	public List<CidadeBean> listaTodos() {
		Criteria c = session.createCriteria(CidadeBean.class);
		return c.list();
	}
}

meu CONTROLLER esta da seguinte forma:

@Resource
public class CidadeController {

	private CidadeDao dao;
	
	private Result result;
	
	private Validator validator;
	
	public CidadeController(CidadeDao dao, Result result, Validator validator) {
		this.dao = dao;
		this.result = result;
		this.validator = validator;
	}
	
	@Get
	@Path("/cidade")
	public List<CidadeBean> lista() {
		return dao.listaTodos();
	}
	
	public void form() {
		
	}
	
	public void adiciona(final CidadeBean cidade) {
		validator.checking(new Validations() {{
			that(!cidade.getDescricao().isEmpty(), "cidade.descricao", "descricao.vazio");
			that(!cidade.getEstado().isEmpty(), "cidade.estado", "estado.vazio");
		}});
		
		validator.onErrorUsePageOf(CidadeController.class).form();
		
		dao.adiciona(cidade);
		
		result.redirectTo(CidadeController.class).lista();
	}
}

meu web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>recap</display-name>
  <filter>
    <filter-name>vraptor</filter-name>
    <filter-class>br.com.caelum.vraptor.VRaptor</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>vraptor</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
  </filter-mapping>
  <context-param>
    <param-name>br.com.caelum.vraptor.packages</param-name>
    <param-value>
        br.com.caelum.vraptor.util.hibernate
    </param-value>
  </context-param>
  <context-param>
    <param-name>br.com.caelum.vraptor.provider</param-name>
    <param-value>br.com.caelum.vraptor.util.hibernate.HibernateCustomProvider</param-value> 
  </context-param>
</web-app>

meu hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1/recap</property>
        <property name="hibernate.connection.username">recap</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

		<property name="show_sql">true</property>
		<property name="format_sql">true</property>

		<mapping class="br.com.dbnet.recap.model.auxiliar.CidadeBean"></mapping>
    </session-factory>
</hibernate-configuration>

porém quando tento acessar a pagina para listar as cidades da as seguintes exceções:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cidadeController': Unsatisfied dependency expressed through constructor argument with index 0 of type [br.com.dbnet.recap.dao.auxiliar.CidadeDao]: : Error creating bean with name 'cidadeDao': Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.Session]: : Error creating bean with name 'br.com.caelum.vraptor.util.hibernate.SessionCreator': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionCreator': Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'br.com.caelum.vraptor.util.hibernate.SessionCreator': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionCreator': Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cidadeDao': Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.Session]: : Error creating bean with name 'br.com.caelum.vraptor.util.hibernate.SessionCreator': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionCreator': Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'br.com.caelum.vraptor.util.hibernate.SessionCreator': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionCreator': Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [br.com.caelum.vraptor.plugin.hibernate4.SessionFactoryCreator, br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator]

eu já tentei criar conforme o exemplo da Apostila FJ28, as classes SessionCreator e SessionCreatorFactory, mas o erro fica igual.

alguma sugestão???

8 Respostas

gabrielmskate

Da uma olhada aqui: https://github.com/garcia-jj/vraptor-plugin-hibernate4
Talvez ajude
Abraço

macspace

Dei uma verificada no link que você me passou e fiz as seguintes mudanças:

no meu web.xml esta:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>recap</display-name>
  <filter>
    <filter-name>vraptor</filter-name>
    <filter-class>br.com.caelum.vraptor.VRaptor</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>vraptor</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
  </filter-mapping>
</web-app>

agora fica dando o seguinte erro:

Caused by: java.sql.SQLException: No suitable driver found for jdbc:postgresql://127.0.0.1/recap
	at java.sql.DriverManager.getConnection(Unknown Source)
	at java.sql.DriverManager.getConnection(Unknown Source)
	at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:192)
	at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:278)
	at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)

já fiz a troca do arquivo hibernate-c3p0-4.1.2.Final por uma versão mais antiga hibernate-c3p0-4.1.1.Final, e mesmo assim continua na mesma.

alguma idéia???

macspace

Voltei a versão do Hibernate para a 4.1.1, ai deu tudo certo.

[]'s

G

Engraçado que você é o segundo aqui no GUJ que tem o mesmo erro. Creio que o pessoal do Hibernate se perdeu na documentação :frowning:

anaylton

garcia-jj, Tive esse mesmo problema da conexão usando o seu plugin
fui no pom do plugin que você criou e mudei as versões do hibernate-core e do hibernate-entitymanager da 4.1.2 para a 4.1.4.Final e funcionou…
o problema é com essa versão do hibernate

Pra não ter que fazer essa alteração na mão, tem como criar uma outra versão do seu plugin com a versão mais nova do hibernate??
ou, se você quiser, posso te ajudar e alterar lá pra você?

G

anaylton:
garcia-jj, Tive esse mesmo problema da conexão usando o seu plugin
fui no pom do plugin que você criou e mudei as versões do hibernate-core e do hibernate-entitymanager da 4.1.2 para a 4.1.4.Final e funcionou…
o problema é com essa versão do hibernate

Pra não ter que fazer essa alteração na mão, tem como criar uma outra versão do seu plugin com a versão mais nova do hibernate??
ou, se você quiser, posso te ajudar e alterar lá pra você?

Mande um pull request.

Abraço

anaylton

Feito!

Abraço!

anaylton

Cara, tu acha que em quanto tempo essa versão nova vai estar disponível pra download no repositório do maven?

Criado 12 de abril de 2012
Ultima resposta 31 de jul. de 2012
Respostas 8
Participantes 4