Boa noite estou tentando conectar no banco com hibernate e não consigo segue os arquivos:
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>
<!-- CONFIGURANDO O HIbernate -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/NUTECDB</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">debian23</property>
<!-- USADO PELO HIBERNATE PARA SE COMUNICAR COM O BD -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="pool_size">10 </property>
<mapping class="br.com.caelum.vraptor.mydvds.model.User"/>
</session-factory>
</hibernate-configuration>
GeraBanco.java
package br.com.caelum.vraptor.mydvds.validation;
/**
*
* @author junior
*/
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class GeraBanco {
public static void main(String[] args) {
AnnotationConfiguration conf = new AnnotationConfiguration();
conf.configure();
SchemaExport se = new SchemaExport(conf);
se.create(true, true);
}
}
Usuario.java
package br.com.caelum.vraptor.mydvds.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.SessionScoped;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
@Entity
@Component
@SessionScoped
public class User {
// Hibernate validator's annnotations/rules
@Id
@NotNull
@Length(min = 3, max = 20)
private String login;
// Hibernate validator's annnotations/rules
@NotNull
@Length(min = 6, max = 20)
private String password;
// Hibernate validator's annnotations/rules
@NotNull
@Length(min = 3, max = 100)
private String name;
// user to dvd mapping,
@OneToMany(mappedBy="owner")
private Set<DvdCopy> copies;
public Set<DvdCopy> getCopies() {
if (copies == null) {
copies = new HashSet<DvdCopy>();
}
return copies;
}
public void setCopies(Set<DvdCopy> dvds) {
this.copies = dvds;
}
public Set<Dvd> getDvds() {
return new HashSet<Dvd>(Collections2.transform(getCopies(), new Function<DvdCopy, Dvd>() {
public Dvd apply(DvdCopy copy) {
return copy.getDvd();
}
}));
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
erro
HTTP Status 500 -
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘hibernateTransactionInterceptor’: 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]: : Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: br.com.caelum.vraptor.mydvds.model.User.copies[br.com.caelum.vraptor.mydvds.model.DvdCopy]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: br.com.caelum.vraptor.mydvds.model.User.copies[br.com.caelum.vraptor.mydvds.model.DvdCopy]; 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]: : Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: br.com.caelum.vraptor.mydvds.model.User.copies[br.com.caelum.vraptor.mydvds.model.DvdCopy]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: br.com.caelum.vraptor.mydvds.model.User.copies[br.com.caelum.vraptor.mydvds.model.DvdCopy]
note The full stack traces of the exception and its root causes are available in the GlassFish v3 logs.
GlassFish v3
naõ roda …
jr
olhe a exceção:
org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: br.com.caelum.vraptor.mydvds.model.User.copies[br.com.caelum.vraptor.mydvds.model.DvdCopy]
é só mapear a classe br.com.caelum.vraptor.mydvds.model.DvdCopy no hibernate.cfg.xml:
<mapping class="br.com.caelum.vraptor.mydvds.model.DvdCopy"/>
Obrigado Lucas !
persiste ! já tentei de tudo …
HTTP Status 500 -
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘hibernateTransactionInterceptor’: 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]: : Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on br.com.caelum.vraptor.mydvds.model.DvdCopy.dvd references an unknown entity: br.com.caelum.vraptor.mydvds.model.Dvd; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on br.com.caelum.vraptor.mydvds.model.DvdCopy.dvd references an unknown entity: br.com.caelum.vraptor.mydvds.model.Dvd; 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]: : Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on br.com.caelum.vraptor.mydvds.model.DvdCopy.dvd references an unknown entity: br.com.caelum.vraptor.mydvds.model.Dvd; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘br.com.caelum.vraptor.util.hibernate.SessionFactoryCreator’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactoryCreator’: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on br.com.caelum.vraptor.mydvds.model.DvdCopy.dvd references an unknown entity: br.com.caelum.vraptor.mydvds.model.Dvd
note The full stack traces of the exception and its root causes are available in the GlassFish v3 logs.
GlassFish v3
gera banco da isso quando rodo:
================================ AGORA FICOU + - ==============================
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>
<!-- CONFIGURANDO O HIbernate -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/NUTECDB</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">debian23</property>
<!-- USADO PELO HIBERNATE PARA SE COMUNICAR COM O BD -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="pool_size">10 </property>
<mapping class="br.com.caelum.vraptor.mydvds.model.User"/>
<mapping class="br.com.caelum.vraptor.mydvds.model.Dvd"/>
<mapping class="br.com.caelum.vraptor.mydvds.model.DvdCopy"/>
</session-factory>
</hibernate-configuration>
HTTP Status 500 -
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.hibernate.exception.GenericJDBCException: Cannot open connection
note The full stack traces of the exception and its root causes are available in the GlassFish v3 logs.
GlassFish v3
aponta este :
at br.com.caelum.vraptor.mydvds.dao.DefaultUserDao.find(DefaultUserDao.java:42)
at br.com.caelum.vraptor.mydvds.controller.HomeController.login(HomeController.java:44)
para esta 42 e 44
@Post
public void login(String login, String password) {
// search for the user in the database
final User currentUser = dao.find(login, password); *********** 44
public User find(String login, String password) {
String hql = "from User u where u.login = :login and u.password = :password";
Query query = session.createQuery(hql)
.setParameter("login", login)
.setParameter("password", password);
return (User) query.uniqueResult(); **************42
}
qual SQL ele tá gerando? dá uma olhada no console…
dá uma olhada nas tabelas que foram criadas no banco de dados, e ve se elas têm os mesmos campos que as suas classes…
Lucas Agora são 5 da manha ! madruguei ! heheh
consigo conectar no banco pelo meu progrma: gerar tabelas com uma classe gerar banco !
so que na hora de mostrar no navegador da isto :
SPRING ALGUMA COISA !
HTTP Status 500 -
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.IllegalStateException: There are two rules that matches the uri ‘/’ with method GET: [[FixedMethodStrategy: uri / methods [GET]], [FixedMethodStrategy: uri / methods [GET]]] with same priority. Consider using @Path priority attribute.
note The full stack traces of the exception and its root causes are available in the GlassFish v3 logs.
GlassFish v3
NO GLASS :
WARNING: StandardWrapperValve[default]: PWC1406: Servlet.service() for servlet default threw exception
java.lang.IllegalStateException: There are two rules that matches the uri '/' with method GET: [[FixedMethodStrategy: uri / methods [GET]], [FixedMethodStrategy: uri / methods [GET]]] with same priority. Consider using @Path priority attribute.
at br.com.caelum.vraptor.http.route.DefaultRouter.checkIfThereIsAnotherRoute(DefaultRouter.java:106)
at br.com.caelum.vraptor.http.route.DefaultRouter.parse(DefaultRouter.java:97)
at br.com.caelum.vraptor.http.DefaultResourceTranslator.translate(DefaultResourceTranslator.java:52)
at br.com.caelum.vraptor.interceptor.ResourceLookupInterceptor.intercept(ResourceLookupInterceptor.java:64)
at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:46)
at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:59)
at br.com.caelum.vraptor.core.DefaultRequestExecution.execute(DefaultRequestExecution.java:62)
at br.com.caelum.vraptor.VRaptor$1.insideRequest(VRaptor.java:91)
at br.com.caelum.vraptor.ioc.spring.SpringProvider.provideForRequest(SpringProvider.java:55)
at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:88)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:636)
Fiz isto :
1 - baixei mydvds
2 - importei par netbeans
3 - ajustei as pastas
4 - editei hibernate.cfg.xml
5 - criei uma classe gerabanco.java
6 - mudei a classe User para Usuario, pois tava dando erro…
7- Rodei o gera banco ==PEGOU FILE=
8 - fui no banco e tava la as tabelas
9- na hora que rodo tudo e vou no navegador :
http://localhost:8080/vraptor-mydvds-3.0/
http://localhost:8080/vraptor-mydvds-3.0/home/login
da estes erro ai em cima !
Erro do VRaptor que nao funciona com PostGreSQL ?
Erro do Spring configuração ?
PARO POR AQUI !
Abraço !
Não mexo com VRaptor, entretanto só precisei ler a excessão. Vc leu?
O último erro não tem nada a ver com o banco de dados, nem com configuração do Spring…
O que acontece é que tem mais de uma logica anotada com @Path ("/") que vc provavelmente
copiou do IndexController… Você não precisa colocar os @Path nas suas lógicas, só quando você
quiser mudar a convenção: CarroController.anda() ==> /carro/anda
[]'s
davidbuzatto e lucas Bom dia !
Eu não mudei anda no MYDVDS ... simplesmente mudei o hibernate.cfg.xml ... e coloquei o drive do postgresql no meu clas path.. Logo eu acho que era para funcionar.. quando eu executo o MYDVDS sem modificar nada cai na tela de login e senha normalmente sem erro.. mais quando eu mudo no hibernate.cfg.xml ele buga.
Precisa de alguma coisa que eu não sei para usar esse exemplo em banco como mysql ou postgre?
Arbaço !
Bom pessoal estou refazendo tudo do Zero !
Usarios.java
package br.com.caelum.vraptor.global.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.SessionScoped;
@Entity
@Component
@SessionScoped
public class Usuarios implements Serializable {
@Id
@NotNull
@Length(min = 3, max = 20)
private String login;
@NotNull
@Length(min = 6, max = 20)
private String password;
@NotNull
@Length(min = 3, max = 100)
private String name;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UsuariosDao.java
package br.com.caelum.vraptor.global.dao;
import java.util.List;
import br.com.caelum.vraptor.global.model.Usuarios;
public interface UsuariosDao {
Usuarios find(String login, String password);
Usuarios find(String login);
void adiciona(Usuarios usuarios);
void refresh(Usuarios usuarios);
void update(Usuarios usuarios);
List<Usuarios> listAll();
public List<Usuarios> listaTudo(); //criado
}
UsuariosController.java
package br.com.caelum.vraptor.global.controller;
import java.util.ArrayList;
import java.util.List;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.global.dao.UsuariosDao;
import br.com.caelum.vraptor.global.interceptor.UsuariosInfo;
import br.com.caelum.vraptor.global.model.Usuarios;
import br.com.caelum.vraptor.view.Results;
@Resource
public class UsuariosController {
private final Validator validator;
private final Result result;
private final UsuariosInfo UsuariosInfo;
private final UsuariosDao dao; // seta o dao
public UsuariosController(UsuariosDao dao, UsuariosInfo UsuariosInfo,
Result result, Validator validator) {
this.dao = dao;
this.result = result;
this.validator = validator;
this.UsuariosInfo = UsuariosInfo;
}
@Path("/usuarios") //Lista usuarios
@Get
public void lista() {
List<Usuarios> Usuarios = new ArrayList<Usuarios>();
result.include("Usuarios", Usuarios);
}
@Path("/usuarios") //Adiciona usuarios
@Post
public void adiciona(Usuarios usuarios){
dao.adiciona(usuarios);
result.use(Results.logic()).redirectTo(UsuariosController.class).lista();
}
@Path("/usuarios") //visualiza usuarios
@Get
public void ver(Usuarios Usuarios) {
this.dao.refresh(Usuarios);
result.include("Usuarios", Usuarios);
}
public void formulario() {
// povoa campos
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>global</display-name>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>messages</param-value>
</context-param>
<context-param>
<param-name>br.com.caelum.vraptor.packages</param-name>
<param-value>br.com.caelum.vraptor.global</param-value>
</context-param>
<context-param>
<param-name>br.com.caelum.vraptor.provider</param-name>
<param-value>br.com.caelum.vraptor.global.provider.CustomProvider</param-value>
</context-param>
<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>
<error-page>
<exception-type>br.com.caelum.vraptor.global.interceptor.AuthenticationException</exception-type>
<location>/index.jsp</location>
</error-page>
</web-app>
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>
<!-- CONFIGURANDO O HIbernate -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/NUTECBD</property>
<property name="hibernate.connectionUsuarios.name">root</property>
<property name="hibernate.connection.password">debian23</property>
<!-- USADO PELO HIBERNATE PARA SE COMUNICAR COM O BD -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="pool_size">10 </property>
<property name="hibernate.transaction.flush_before_completion">true</property>
<property name="hibernate.cache.provider_class">10</property>
<property name="hibernate.jdbc.fetch_size">10</property>
<!-- CLASSES -->
<mapping class="br.com.caelum.vraptor.global.model.Usuarios"/>
<event type="auto-flush"/>
</session-factory>
</hibernate-configuration>
lucascs bOA Tarde !
Eu para eliminar possibilidades de erros deixei minhas classes bem simples.
1 - Usuarios.java
2- UsuariosDao.java
3- UsuariosController.java
4- adiciona.jsp
5- lista.jsp
6- procura.jsp
7- ver.jsp
usuarios.java
package br.com.caelum.vraptor.global.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.SessionScoped;
@Entity
@Component
@SessionScoped
public class Usuarios implements Serializable {
@Id
@NotNull
@Length(min = 3, max = 20)
private String login;
@NotNull
@Length(min = 6, max = 20)
private String password;
@NotNull
@Length(min = 3, max = 100)
private String nome;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getName() {
return nome;
}
public void setName(String name) {
this.nome = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
usuariosdao.java
package br.com.caelum.vraptor.global.dao;
import java.util.List;
import br.com.caelum.vraptor.global.model.Usuarios;
public interface UsuariosDao {
Usuarios find(String login, String password);
Usuarios find(String login);
void adiciona(Usuarios usuarios);
void refresh(Usuarios usuarios);
void update(Usuarios usuarios);
List<Usuarios> listAll();
public List<Usuarios> listaTudo(); //criado
}
usuarioscontroller.java
package br.com.caelum.vraptor.global.controller;
import java.util.ArrayList;
import java.util.List;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.global.dao.UsuariosDao;
import br.com.caelum.vraptor.global.interceptor.UsuariosInfo;
import br.com.caelum.vraptor.global.model.Usuarios;
import br.com.caelum.vraptor.view.Results;
@Resource
public class UsuariosController {
private final Validator validator;
private final Result result;
private final UsuariosInfo UsuariosInfo;
private final UsuariosDao dao; // seta o dao
public UsuariosController(UsuariosDao dao, UsuariosInfo UsuariosInfo,
Result result, Validator validator) {
this.dao = dao;
this.result = result;
this.validator = validator;
this.UsuariosInfo = UsuariosInfo;
}
@Path("/usuarios") //Lista usuarios
@Get
public void lista() {
List<Usuarios> Usuarios = new ArrayList<Usuarios>();
result.include("Usuarios", Usuarios);
}
@Path("/usuarios") //Adiciona usuarios
@Post
public void adiciona(Usuarios usuarios){
dao.adiciona(usuarios);
result.use(Results.logic()).redirectTo(UsuariosController.class).lista();
}
@Path("/usuarios") //visualiza usuarios
@Get
public void ver(Usuarios Usuarios) {
this.dao.refresh(Usuarios);
result.include("Usuarios", Usuarios);
}
public void formulario() {
// povoa campos
}
}
formulario.jsp *********para add dados dos usuarios
<%@ include file="../home/header.jsp" %>
<form action="<c:url value="/usuarios/adiciona" />" name="registerForm" method="post">
<fieldset>
<legend>.:Cadastrar no Sistema :.</legend>
<label for="usuarios.login"><fmt:message key="login"/></label>
<input type="text" name="usuarios.login" value="${usuarios.login }"/>
<label for="usuarios.password"><fmt:message key="password"/></label>
<input type="password" name="usuarios.password" value="${usuarios.password }"/>
<button type="submit" id="usuarios.submit" value="Salvar"><fmt:message key="send"/></button>
</fieldset>
</form>
<%@ include file="../home/footer.jsp" %>er.jsp" %>
lista.jsp *** par listar usuarios
<form>
<fieldset>
<ul>
<c:forEach items="${usuariosLista}" var="usuarios">
<li> ${usuarios.login} - ${usuarios.login} </li>
<li> ${usuarios.nome} - ${usuarios.nome} </li>
<li> ${usuarios.password} - ${usuarios.password} </li>
</c:forEach>
</ul>
</fieldset>
</form>
Opá, e ai blz?
Gostaria de saber como vc conseguiu e se conseguiu resolver o seu problema?
vc já viu se não é isto aki:
[code]
@Path ("/usuarios") //Lista usuarios
@Get
public void lista() {
List Usuarios = new ArrayList();
result.include(“Usuarios”, Usuarios);
}
@Path ("/usuarios") //visualiza usuarios
@Get
public void ver(Usuarios Usuarios) {
this.dao.refresh(Usuarios);
result.include(“Usuarios”, Usuarios);
} [/code]
o erro: There are two rules that matches the uri '/'
Quer dizer: Existem duas regras que corresponde ao URI ‘/’
eu tbm estou tendo o mesmo erro que vc mas no meu caso, não tem nenhuma regra que corresponde ao mesmo URI.
espero resposta!
sim é isso mesmo ! Muito Obrigado !
Mudei para JSF + RichFaces + Xhtml + Hibernate… mas VRaptor é Otimo !
abraço !
[quote=juniorsatanas]sim é isso mesmo ! Muito Obrigado !
Mudei para JSF + RichFaces + Xhtml + Hibernate… mas VRaptor é Otimo !
abraço !
[/quote]
haaaaa… blz!
Mas ainda não sei o que tem de errado no meu!
vou usar VRaptor nem que eu tenha que aprender java de novo!
abs
Ramon.Onix tentei por essa ideia aqui… netbeans + vraptor , necas eclipse + jsf foda !
Vixi então to fud@#$% pq eu só uso o Netbeans[+VRaptor +Hibernate +MySql tudo no Glassfish v3-Prelude] mas até agora meu projeto tem dado certo no Netbeans, mas ai fui dar continuidade usando a apostila FJ-28 da caelum, mas na parte de verbos, mudança das uri’s das lógicas, deu pau.
vou pular esta etapa, não sei se é tão importante te assim essa parte, se for mesmo necessário, volto e refaço…
mas por enquanto, vamo que vamo… ta tudo redondo!
abs