Guevara 15 de set. de 2010
Olá!
Onde vc está mapeando a Universidade? Não deveria estar no seu hibernate.cfg.xml? Quando se usa anotação, coloca-se o @Entity na classe, e depois é só adicionar ao HibernateUtil.
public class HibernateUtil {
private static SessionFactory factory ;
static {
AnnotationConfiguration cfg = new AnnotationConfiguration ();
cfg . addAnnotatedClass ( Universidade . class );
cfg . addAnnotatedClass ( OutraClasse . class );
factory = cfg . buildSessionFactory ();
}
public Session getSession () {
return factory . openSession ();
}
}
Veja se não é falta de mapeamento.
[]s
jaziel.rc 15 de set. de 2010
1- Tu está usando Hibernate ou JPA?
O stacktrace do sua exception é de JPA, não de Hibernate.
Considerando que tu usa JPA, tu deveria ter o persistence.xml, com as configurações necessárias, e o erro que está dando no caso, seria que seu persistence.xml não tem uma
<persistence-unit name="Universidade" > configurada corretamente, que no caso é chamada na seguinte linha
EntityManager manager = Persistence.createEntityManagerFactory("Universidade").createEntityManager();
De uma olhada por tutorial, aqui mesmo no guj tem alguns bons, sobre JPA, Hibernate e as diferenças.
Guevara 15 de set. de 2010
É, têm essa que o zoren falou, persistence.xml dentro da pasta META-INF localizada na sua pasta /src do projeto.
[]s
marlonmca 15 de set. de 2010
Então… eu fui seguindo o que vcs disseram aqui no fórum. Criei o arquivo persistence e ai, como sempre, foi dando outros erros e eu fui pesquisando e resolvendo até que chegou nesse:
será que isso tem algo a ver com a versão do hibernate que zoren disse?
Caused by : javax . persistence . PersistenceException : Invalid persistence . xml .
Error parsing XML ( line -1 : column -1 ) : cvc - elt .1 : Cannot find the declaration of element ' persistence ' .
at org . hibernate . ejb . packaging . PersistenceXmlLoader . loadURL ( PersistenceXmlLoader . java : 145 )
at org . hibernate . ejb . packaging . PersistenceXmlLoader . deploy ( PersistenceXmlLoader . java : 168 )
at org . hibernate . ejb . Ejb3Configuration . configure ( Ejb3Configuration . java : 310 )
at org . hibernate . ejb . HibernatePersistence . createEntityManagerFactory ( HibernatePersistence . java : 55 )
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 48 )
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 32 )
at br . com . universidade . dao . UniversidadeDao . getListaCompleta ( UniversidadeDao . java : 85 )
at sun . reflect . NativeMethodAccessorImpl . invoke0 ( Native Method )
at sun . reflect . NativeMethodAccessorImpl . invoke ( NativeMethodAccessorImpl . java : 39 )
at sun . reflect . DelegatingMethodAccessorImpl . invoke ( DelegatingMethodAccessorImpl . java : 25 )
at java . lang . reflect . Method . invoke ( Method . java : 597 )
at javax . el . BeanELResolver . getValue ( BeanELResolver . java : 64 )
at javax . el . CompositeELResolver . getValue ( CompositeELResolver . java : 55 )
at com . sun . faces . el . FacesCompositeELResolver . getValue ( FacesCompositeELResolver . java : 71 )
at org . apache . el . parser . AstValue . getValue ( AstValue . java : 169 )
at org . apache . el . ValueExpressionImpl . getValue ( ValueExpressionImpl . java : 192 )
at com . sun . faces . facelets . el . TagValueExpression . getValue ( TagValueExpression . java : 106 )
... 32 more
15 / 09 / 2010 15 : 33 : 17 org . apache . catalina . core . StandardWrapperValve invoke
GRAVE : Servlet . service () for servlet [ Faces Servlet ] in context with path [ / universidade2 ] threw exception [ Invalid persistence . xml .
Error parsing XML ( line -1 : column -1 ) : cvc - elt .1 : Cannot find the declaration of element ' persistence ' .
] with root cause
javax . persistence . PersistenceException : Invalid persistence . xml .
Error parsing XML ( line -1 : column -1 ) : cvc - elt .1 : Cannot find the declaration of element ' persistence ' .
Guevara 15 de set. de 2010
<?xml version="1.0" encoding="UTF-8"?>
<persistence version= "2.0" xmlns= "http://java.sun.com/xml/ns/persistence"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >
<persistence-unit name= "default" transaction-type= "RESOURCE_LOCAL" >
<provider> org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name= "hibernate.dialect" value= "org.hibernate.dialect.PostgreSQLDialect" />
<property name= "javax.persistence.jdbc.url" value= "jdbc:postgresql://localhost/meubanco" />
<property name= "javax.persistence.jdbc.driver" value= "org.postgresql.Driver" />
<property name= "javax.persistence.jdbc.password" value= "123456" />
<property name= "javax.persistence.jdbc.user" value= "postgres" />
<property name= "hibernate.hbm2ddl.auto" value= "update" />
<property name= "hibernate.show_sql" value= "true" />
<property name= "hibernate.format_sql" value= "true" />
</properties>
</persistence-unit>
</persistence>
Tente esta configuração, troque os dados referente ao banco, usuario e senha.
marlonmca 15 de set. de 2010
Funcionou =)
mas deu outro erro: (se alguém souber eu agradeço, mas enquanto isso vou pesquisando mais um erro) :
eu adicionei esta linha no persistence, mas ainda assim não funcionou: br.com.universidade.entity.Universidade
Caused by : javax . persistence . PersistenceException : No Persistence provider for EntityManager named universidade
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 54 )
at javax . persistence . Persistence . createEntityManagerFactory ( Persistence . java : 32 )
at br . com . universidade . dao . UniversidadeDao . getListaCompleta ( UniversidadeDao . java : 85 )
at sun . reflect . NativeMethodAccessorImpl . invoke0 ( Native Method )
at sun . reflect . NativeMethodAccessorImpl . invoke ( NativeMethodAccessorImpl . java : 39 )
at sun . reflect . DelegatingMethodAccessorImpl . invoke ( DelegatingMethodAccessorImpl . java : 25 )
at java . lang . reflect . Method . invoke ( Method . java : 597 )
at javax . el . BeanELResolver . getValue ( BeanELResolver . java : 64 )
at javax . el . CompositeELResolver . getValue ( CompositeELResolver . java : 55 )
at com . sun . faces . el . FacesCompositeELResolver . getValue ( FacesCompositeELResolver . java : 71 )
at org . apache . el . parser . AstValue . getValue ( AstValue . java : 169 )
at org . apache . el . ValueExpressionImpl . getValue ( ValueExpressionImpl . java : 192 )
at com . sun . faces . facelets . el . TagValueExpression . getValue ( TagValueExpression . java : 106 )
... 32 more
15 / 09 / 2010 16 : 18 : 42 org . apache . catalina . core . StandardWrapperValve invoke
GRAVE : Servlet . service () for servlet [ Faces Servlet ] in context with path [ / universidade2 ] threw exception [ No Persistence provider for EntityManager named universidade ] with root cause
javax . persistence . PersistenceException : No Persistence provider for EntityManager named universidade
...
Guevara 15 de set. de 2010
É só substituir pelos seus dados no persistence.xml que postei, não precisa adicionar mais nada. Poste seu persistence.xml pra ver como ficou.
marlonmca 15 de set. de 2010
<?xml version="1.0" encoding="UTF-8"?>
<persistence version= "2.0" xmlns= "http://java.sun.com/xml/ns/persistence"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >
<persistence-unit name= "default" transaction-type= "RESOURCE_LOCAL" >
<provider> org.hibernate.ejb.HibernatePersistence</provider>
<class> br.com.universidade.entity.Universidade</class>
<properties>
<property name= "hibernate.dialect" value= "org.hibernate.dialect.PostgreSQLDialect" />
<property name= "javax.persistence.jdbc.url" value= "jdbc:postgresql://127.0.0.1:5432/universidade" />
<property name= "javax.persistence.jdbc.driver" value= "org.postgresql.Driver" />
<property name= "javax.persistence.jdbc.password" value= "postgres" />
<property name= "javax.persistence.jdbc.user" value= "postgres" />
<property name= "hibernate.hbm2ddl.auto" value= "update" />
<property name= "hibernate.show_sql" value= "true" />
<property name= "hibernate.format_sql" value= "true" />
</properties>
</persistence-unit>
</persistence>
Roger75 15 de set. de 2010
marlonmca:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version= "2.0" xmlns= "http://java.sun.com/xml/ns/persistence"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >
<persistence-unit name= "default" transaction-type= "RESOURCE_LOCAL" >
<provider> org.hibernate.ejb.HibernatePersistence</provider>
<class> br.com.universidade.entity.Universidade</class>
<properties>
<property name= "hibernate.dialect" value= "org.hibernate.dialect.PostgreSQLDialect" />
<property name= "javax.persistence.jdbc.url" value= "jdbc:postgresql://127.0.0.1:5432/universidade" />
<property name= "javax.persistence.jdbc.driver" value= "org.postgresql.Driver" />
<property name= "javax.persistence.jdbc.password" value= "postgres" />
<property name= "javax.persistence.jdbc.user" value= "postgres" />
<property name= "hibernate.hbm2ddl.auto" value= "update" />
<property name= "hibernate.show_sql" value= "true" />
<property name= "hibernate.format_sql" value= "true" />
</properties>
</persistence-unit>
</persistence>
O nome do persistence-unit está como "default". Mude para "Universidade"
marlonmca 15 de set. de 2010
Mudei. Agora ta dando outro erro:
Caused by : org . hibernate . AnnotationException : No identifier specified for entity : br . com . universidade . entity . Universidade
at org . hibernate . cfg . InheritanceState . determineDefaultAccessType ( InheritanceState . java : 272 )
at org . hibernate . cfg . InheritanceState . getElementsToProcess ( InheritanceState . java : 227 )
at org . hibernate . cfg . AnnotationBinder . bindClass ( AnnotationBinder . java : 705 )
at org . hibernate . cfg . AnnotationConfiguration . processArtifactsOfType ( AnnotationConfiguration . java : 636 )
at org . hibernate . cfg . AnnotationConfiguration . secondPassCompile ( AnnotationConfiguration . java : 359 )
at org . hibernate . cfg . Configuration . buildSessionFactory ( Configuration . java : 1377 )
at org . hibernate . cfg . AnnotationConfiguration . buildSessionFactory ( AnnotationConfiguration . java : 954 )
at br . com . universidade . util . HibernateUtil . < clinit > ( HibernateUtil . java : 17 )
... 43 more
15 / 09 / 2010 17 : 59 : 34 org . apache . catalina . core . StandardWrapperValve invoke
GRAVE : Servlet . service () for servlet [ Faces Servlet ] in context with path [ / universidade2 ] threw exception [ null ] with root cause
org . hibernate . AnnotationException : No identifier specified for entity : br . com . universidade . entity . Universidade
at org . hibernate . cfg . InheritanceState . determineDefaultAccessType ( InheritanceState . java : 272 )
at org . hibernate . cfg . InheritanceState . getElementsToProcess ( InheritanceState . java : 227 )
at org . hibernate . cfg . AnnotationBinder . bindClass ( AnnotationBinder . java : 705 )
at org . hibernate . cfg . AnnotationConfiguration . processArtifactsOfType ( AnnotationConfiguration . java : 636 )
at org . hibernate . cfg . AnnotationConfiguration . secondPassCompile ( AnnotationConfiguration . java : 359 )
at org . hibernate . cfg . Configuration . buildSessionFactory ( Configuration . java : 1377 )
at org . hibernate . cfg . AnnotationConfiguration . buildSessionFactory ( AnnotationConfiguration . java : 954 )
at br . com . universidade . util . HibernateUtil . < clinit > ( HibernateUtil . java : 17 )
at br . com . universidade . dao . UniversidadeDao . getListaCompleta ( UniversidadeDao . java : 94 )
at sun . reflect . NativeMethodAccessorImpl . invoke0 ( Native Method )
at sun . reflect . NativeMethodAccessorImpl . invoke ( NativeMethodAccessorImpl . java : 39 )
at sun . reflect . DelegatingMethodAccessorImpl . invoke ( DelegatingMethodAccessorImpl . java : 25 )
at java . lang . reflect . Method . invoke ( Method . java : 597 )
at javax . el . BeanELResolver . getValue ( BeanELResolver . java : 64 )
at javax . el . CompositeELResolver . getValue ( CompositeELResolver . java : 55 )
at com . sun . faces . el . FacesCompositeELResolver . getValue ( FacesCompositeELResolver . java : 71 )
at org . apache . el . parser . AstValue . getValue ( AstValue . java : 169 )
at org . apache . el . ValueExpressionImpl . getValue ( ValueExpressionImpl . java : 192 )
at com . sun . faces . facelets . el . TagValueExpression . getValue ( TagValueExpression . java : 106 )
at javax . faces . component . ComponentStateHelper . eval ( ComponentStateHelper . java : 190 )
at javax . faces . component . ComponentStateHelper . eval ( ComponentStateHelper . java : 178 )
at javax . faces . component . UIData . getValue ( UIData . java : 554 )
at javax . faces . component . UIData . getDataModel ( UIData . java : 1278 )
at javax . faces . component . UIData . setRowIndex ( UIData . java : 447 )
at com . sun . faces . renderkit . html_basic . TableRenderer . encodeBegin ( TableRenderer . java : 77 )
at javax . faces . component . UIComponentBase . encodeBegin ( UIComponentBase . java : 824 )
at javax . faces . component . UIData . encodeBegin ( UIData . java : 937 )
at javax . faces . component . UIComponent . encodeAll ( UIComponent . java : 1641 )
at javax . faces . component . UIComponent . encodeAll ( UIComponent . java : 1646 )
at com . sun . faces . application . view . FaceletViewHandlingStrategy . renderView ( FaceletViewHandlingStrategy . java : 389 )
at com . sun . faces . application . view . MultiViewHandler . renderView ( MultiViewHandler . java : 127 )
at com . sun . faces . lifecycle . RenderResponsePhase . execute ( RenderResponsePhase . java : 117 )
at com . sun . faces . lifecycle . Phase . doPhase ( Phase . java : 97 )
at com . sun . faces . lifecycle . LifecycleImpl . render ( LifecycleImpl . java : 135 )
at javax . faces . webapp . FacesServlet . service ( FacesServlet . java : 311 )
at org . apache . catalina . core . ApplicationFilterChain . internalDoFilter ( ApplicationFilterChain . java : 303 )
at org . apache . catalina . core . ApplicationFilterChain . doFilter ( ApplicationFilterChain . java : 208 )
at org . apache . catalina . core . StandardWrapperValve . invoke ( StandardWrapperValve . java : 243 )
at org . apache . catalina . core . StandardContextValve . invoke ( StandardContextValve . java : 201 )
at org . apache . catalina . core . StandardHostValve . invoke ( StandardHostValve . java : 163 )
at org . apache . catalina . valves . ErrorReportValve . invoke ( ErrorReportValve . java : 108 )
at org . apache . catalina . valves . AccessLogValve . invoke ( AccessLogValve . java : 556 )
at org . apache . catalina . core . StandardEngineValve . invoke ( StandardEngineValve . java : 118 )
at org . apache . catalina . connector . CoyoteAdapter . service ( CoyoteAdapter . java : 401 )
at org . apache . coyote . http11 . Http11Processor . process ( Http11Processor . java : 242 )
at org . apache . coyote . http11 . Http11Protocol$Http11ConnectionHandler . process ( Http11Protocol . java : 267 )
at org . apache . coyote . http11 . Http11Protocol$Http11ConnectionHandler . process ( Http11Protocol . java : 245 )
at org . apache . tomcat . util . net . JIoEndpoint$SocketProcessor . run ( JIoEndpoint . java : 260 )
at java . util . concurrent . ThreadPoolExecutor$Worker . runTask ( ThreadPoolExecutor . java : 886 )
at java . util . concurrent . ThreadPoolExecutor$Worker . run ( ThreadPoolExecutor . java : 908 )
at java . lang . Thread . run ( Thread . java : 619 )
HibernateUtil
public class HibernateUtil {
private static SessionFactory factory ;
static {
AnnotationConfiguration cfg = new AnnotationConfiguration ();
cfg . addAnnotatedClass ( Universidade . class );
factory = cfg . buildSessionFactory (); <====================== O ERRO DA AQUI
}
public Session getSession () {
return factory . openSession ();
}
}
UniversidadeDAO
HibernateUtil hu = new HibernateUtil();
Session session = hu.getSession(); //(Session) manager.getDelegate();
List<Universidade> list = session.createQuery("from universidade").list();
Universidade.java
package br.com.universidade.entity ;
import javax.persistence.Column ;
import javax.persistence.Entity ;
import javax.persistence.GeneratedValue ;
import javax.persistence.GenerationType ;
import javax.persistence.Id ;
import javax.persistence.Table ;
@Entity
@Table ( schema = "client" , name = "universidade" )
public class Universidade {
private int idUniversidade ;
private String nome ;
@Id
@GeneratedValue ( strategy = GenerationType . AUTO )
@Column ( name = "id_universidade" , nullable = false )
public void getIdUniversidade ( int idUniversidade ) {
this . idUniversidade = idUniversidade ;
}
public int setIdUniversidade () {
return idUniversidade ;
}
@Column ( name = "nome" , nullable = true , length = 200 )
public void getNome ( String nome ) {
this . nome = nome ;
}
public String setNome () {
return nome ;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version= "2.0" xmlns= "http://java.sun.com/xml/ns/persistence"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >
<persistence-unit name= "Universidade" transaction-type= "RESOURCE_LOCAL" >
<provider> org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name= "hibernate.dialect" value= "org.hibernate.dialect.PostgreSQLDialect" />
<property name= "javax.persistence.jdbc.url" value= "jdbc:postgresql://127.0.0.1:5432/universidade" />
<property name= "javax.persistence.jdbc.driver" value= "org.postgresql.Driver" />
<property name= "javax.persistence.jdbc.password" value= "postgres" />
<property name= "javax.persistence.jdbc.user" value= "postgres" />
<property name= "hibernate.hbm2ddl.auto" value= "update" />
<property name= "hibernate.show_sql" value= "true" />
<property name= "hibernate.format_sql" value= "true" />
</properties>
</persistence-unit>
</persistence>
desde já grato pela ajuda. =)
Guevara 15 de set. de 2010
Na sua classe UniversidadeDAO poderia ter algo do tipo:
import org.hibernate.Criteria ;
import org.hibernate.Session ;
// import para o pacote do bean Universidade aqui.
public class UniversidadeDAO {
private Session session ;
public UniversidadeDAO ( Session session ) {
this . session = session ;
}
public UniversidadeDAO () {
this . session = new HibernateUtil (). getSession ();
}
public List < Universidade > lista () {
return session . createCriteria ( Universidade . class ). list ();
}
}
Acho que o erro está lá mesmo.
[]s
Andre_Brito 15 de set. de 2010
Se o que o Guevara falou não tiver resolvido o seu problema, coloque as Annotations nos atributos, ao invés de colocar nos métodos. Algo assim:
package br.com.universidade.entity ;
import javax.persistence.Column ;
import javax.persistence.Entity ;
import javax.persistence.GeneratedValue ;
import javax.persistence.GenerationType ;
import javax.persistence.Id ;
import javax.persistence.Table ;
@Entity
@Table ( schema = "client" , name = "universidade" )
public class Universidade {
@Id
@GeneratedValue ( strategy = GenerationType . AUTO )
@Column ( name = "id_universidade" , nullable = false )
private int idUniversidade ;
@Column ( name = "nome" , nullable = true , length = 200 )
private String nome ;
public void getIdUniversidade ( int idUniversidade ) {
this . idUniversidade = idUniversidade ;
}
public int setIdUniversidade () {
return idUniversidade ;
}
public void getNome ( String nome ) {
this . nome = nome ;
}
public String setNome () {
return nome ;
}
}
marlonmca 16 de set. de 2010
Foi o que andre disse. Agora ta ok. =)
Universidade.java
package br.com.universidade.entity ;
import java.io.Serializable ;
import javax.persistence.Column ;
import javax.persistence.Entity ;
import javax.persistence.Id ;
import javax.persistence.Table ;
@Entity
@Table ( schema = "client" , name = "universidade" )
public class Universidade implements Serializable {
private static final long serialVersionUID = 1L ;
@Id
@Column ( name = "id_universidade" , unique = true , nullable = false , updatable = false )
private int idUniversidade ;
@Column ( name = "nome" , nullable = true , length = 200 )
private String nome ;
public void getIdUniversidade ( int idUniversidade ) {
this . idUniversidade = idUniversidade ;
}
public int setIdUniversidade () {
return idUniversidade ;
}
public void getNome ( String nome ) {
this . nome = nome ;
}
public String setNome () {
return nome ;
}
}
UniversidadeDAO.java
public ArrayList < Universidade > getListaCompleta () {
this .session = new HibernateUtil () .getSession () ;
return ( List < Universidade > ) session .createCriteria ( Universidade .class ) .list () ;
}
HibernateUtil.java
package br.com.universidade.util ;
import org.hibernate.Session ;
import org.hibernate.SessionFactory ;
import org.hibernate.cfg.AnnotationConfiguration ;
import br.com.universidade.entity.Universidade ;
public class HibernateUtil {
private static SessionFactory factory ;
static {
AnnotationConfiguration cfg = new AnnotationConfiguration ();
cfg . addAnnotatedClass ( Universidade . class );
factory = cfg . buildSessionFactory ();
}
public Session getSession () {
return factory . openSession ();
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version= "2.0" xmlns= "http://java.sun.com/xml/ns/persistence"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >
<persistence-unit name= "Universidade" transaction-type= "RESOURCE_LOCAL" >
<provider> org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name= "hibernate.dialect" value= "org.hibernate.dialect.PostgreSQLDialect" />
<property name= "javax.persistence.jdbc.url" value= "jdbc:postgresql://127.0.0.1:5432/universidade" />
<property name= "javax.persistence.jdbc.driver" value= "org.postgresql.Driver" />
<property name= "javax.persistence.jdbc.password" value= "postgres" />
<property name= "javax.persistence.jdbc.user" value= "postgres" />
<property name= "hibernate.hbm2ddl.auto" value= "update" />
<property name= "hibernate.show_sql" value= "true" />
<property name= "hibernate.format_sql" value= "true" />
</properties>
</persistence-unit>
</persistence>
Muito obrigado a todos vcs que participaram.
Se não fosse por vcs esse negócio não saia. Espero que esse post ajude a muita gente.
Andre_Brito 16 de set. de 2010
Não se esqueça de colocar as tags de resolvido no título do tópico
E que bom que conseguiu resolver.