Pessoal, Estou criando um projeto usando struts2 com JPA, fiz toda a engenharia reversa do banco de dados que tinha 2 tabelas ( Blog, Comentario ) e o netbeans ja configurou tudo pra mim, até ai blz…
o problema agora é começar a usar, ainda nao consegui persistir um novo objeto no banco e nem recuperar.
Então vamos para o primeiro problema, recuperar os registros que inseri manualmente no banco.
[code]import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import persistencia.Blog;
public class Teste {
public static void main( String args[] ){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistencia");
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("select b from blog b");
List results = query.getResultList();
Iterator iter = results.iterator();
while (iter.hasNext())
{
Blog b = (Blog) iter.next();
System.out.println( b.getTitulo() );
}
}
}
[/code]
ao mandar rodar essa classe eu recebo a mensagem:
init:
deps-module-jar:
deps-ear-jar:
deps-jar:
compile-single:
run-main:
[EL Info]: 2010-02-27 14:35:21.062--ServerSession(11060360)--EclipseLink, version: Eclipse Persistence Services - 2.0.0.v20091127-r5931
[EL Info]: 2010-02-27 14:35:21.562--ServerSession(11060360)--file:/C:/Documents and Settings/Nei/Meus documentos/NetBeansProjects/Trabalho/build/web/WEB-INF/classes/_persistencia login successful
Exception in thread "main" java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Error compiling the query [select b from blog b]. Unknown entity type [blog].
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1328)
at Teste.main(Teste.java:35)
Caused by: Exception [EclipseLink-8034] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [select b from blog b]. Unknown entity type [blog].
at org.eclipse.persistence.exceptions.JPQLException.entityTypeNotFound(JPQLException.java:483)
at org.eclipse.persistence.internal.jpa.parsing.ParseTreeContext.classForSchemaName(ParseTreeContext.java:138)
at org.eclipse.persistence.internal.jpa.parsing.SelectNode.getClassOfFirstVariable(SelectNode.java:327)
at org.eclipse.persistence.internal.jpa.parsing.SelectNode.getReferenceClass(SelectNode.java:316)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.getReferenceClass(ParseTree.java:439)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.adjustReferenceClassForQuery(ParseTree.java:79)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateReadQueryInternal(JPQLParseTree.java:103)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateQuery(JPQLParseTree.java:84)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:202)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:173)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:125)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:109)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1326)
... 1 more
Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 3 segundos)
A Classe entidade existe, foi gerada automaticamente, o código dela é esse:
[code]/*
- To change this template, choose Tools | Templates
- and open the template in the editor.
*/
package persistencia;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
-
@author Nei
*/
@Entity
@Table(name = “blog”, catalog = “ufpr”, schema = “”)
@NamedQueries({
@NamedQuery(name = “Blog.findAll”, query = “SELECT b FROM Blog b”),
@NamedQuery(name = “Blog.findById”, query = “SELECT b FROM Blog b WHERE b.id = :id”),
@NamedQuery(name = “Blog.findByCreatedAt”, query = “SELECT b FROM Blog b WHERE b.createdAt = :createdAt”),
@NamedQuery(name = “Blog.findByUpdatedAt”, query = “SELECT b FROM Blog b WHERE b.updatedAt = :updatedAt”),
@NamedQuery(name = “Blog.findByTitulo”, query = “SELECT b FROM Blog b WHERE b.titulo = :titulo”),
@NamedQuery(name = “Blog.findByAutor”, query = “SELECT b FROM Blog b WHERE b.autor = :autor”)})
public class Blog implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = “id”)
private Integer id;
@Basic(optional = false)
@Column(name = “created_at”)
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
@Basic(optional = false)
@Column(name = “updated_at”)
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
@Basic(optional = false)
@Column(name = “titulo”)
private String titulo;
@Basic(optional = false)
@Lob
@Column(name = “texto”)
private String texto;
@Basic(optional = false)
@Column(name = “autor”)
private String autor;
@OneToMany(cascade = CascadeType.ALL, mappedBy = “blogId”)
private Collection<Comentario> comentarioCollection;public Blog() {
}public Blog(Integer id) {
this.id = id;
}public Blog(Integer id, Date createdAt, Date updatedAt, String titulo, String texto, String autor) {
this.id = id;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.titulo = titulo;
this.texto = texto;
this.autor = autor;
}public Integer getId() {
return id;
}public void setId(Integer id) {
this.id = id;
}public Date getCreatedAt() {
return createdAt;
}public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}public Date getUpdatedAt() {
return updatedAt;
}public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}public String getTitulo() {
return titulo;
}public void setTitulo(String titulo) {
this.titulo = titulo;
}public String getTexto() {
return texto;
}public void setTexto(String texto) {
this.texto = texto;
}public String getAutor() {
return autor;
}public void setAutor(String autor) {
this.autor = autor;
}public Collection<Comentario> getComentarioCollection() {
return comentarioCollection;
}public void setComentarioCollection(Collection<Comentario> comentarioCollection) {
this.comentarioCollection = comentarioCollection;
}@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}@Override
public boolean equals(Object object) {
// TODO: Warning - this method won’t work in the case the id fields are not set
if (!(object instanceof Blog)) {
return false;
}
Blog other = (Blog) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}@Override
public String toString() {
return "persistencia.Blog[id=" + id + "]";
}
}
[/code]
O arquivo persistence.xml também foi gerado automaticamente:
<?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="persistencia" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/ufpr"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
</persistence>
Alguém sabe pq ele diz que minha classe entidade não existe? tentei usar na sql Blog e blog, ambas nao fucionam.
Aprecio a ajuda.
Nei