Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

Tuesday, May 17, 2011

Published 5/17/2011 by with 0 comment

No Persistence provider for EntityManager named

Are you using JPA and getting the error "Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named ..."

You might have used an entity manager as the following code:


public void persist(Object object) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }


And you might have a persistence.xml file as below:

<?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="PersonPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>person.entity.Person</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/persondb"/>
<property name="javax.persistence.jdbc.password" value="mypassword"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
</persistence>


Now see that, this error may happen for any of the following reasons:



1. In the code EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU"); TestPU is passed in the method which must be a valid persistence unit name. In the persistence.xml file the name is defined as persistence-unit name="PersonPU". These two names must be same. So to remove the error the correct code will be :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonPU");

2. If the persistence unit name is correctly used but still the error exists, then confirm that the required jar file containing the JPA implementation classes are available in the classpath. Required jar files for the above code are eclipselink-2.0.0.jar and eclipselink-javax.persistence-2.0.jar

Read More

    email this       edit
Published 5/17/2011 by with 1 comment

is not a known entity type

To understand the error, let us assume that we have the following classes:

1) An entity class
package person.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
 *
 * @author Shamsuddin
 */
@Entity
@Table(name = "person")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"),
    @NamedQuery(name = "Person.findById", query = "SELECT p FROM Person p WHERE p.id = :id"),
    @NamedQuery(name = "Person.findByFirstName", query = "SELECT p FROM Person p WHERE p.firstName = :firstName"),
    @NamedQuery(name = "Person.findByLastName", query = "SELECT p FROM Person p WHERE p.lastName = :lastName"),
    @NamedQuery(name = "Person.findByDateOfBirth", query = "SELECT p FROM Person p WHERE p.dateOfBirth = :dateOfBirth"),
    @NamedQuery(name = "Person.findByEmail", query = "SELECT p FROM Person p WHERE p.email = :email")})
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "date_of_birth")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateOfBirth;
    @Column(name = "email")
    private String email;
    public Person() {
    }
    public Person(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDateOfBirth() {
        return dateOfBirth;
    }
    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @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 Person)) {
            return false;
        }
        Person other = (Person) 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 "person.entity.Person[ id=" + id + " ]";
    }
 
}

2. A java class that encapsulates an EntityManager

package person.manager;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
 *
 * @author Shamsuddin
 */
public class MyEntityManager {
   EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonPU");
   EntityManager em = emf.createEntityManager();
    public void persist(Object object) {
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }
 
}

3. A main class

package person;
import person.entity.Person;
import person.manager.MyEntityManager;
/**
 *
 * @author Shamsuddin
 */
public class PersonMain {
    public static void main(String args[])
    {
        MyEntityManager entityManager = new MyEntityManager();
     
        Person person = new Person();
        person.setFirstName("Shamsuddin");
        person.setLastName("Ahammad");
     
        entityManager.persist(person);
     
     
    }
}


If we run the PersonMain class, in a situation, following error may be encountered:



java.lang.IllegalArgumentException: Object: person.entity.Person[ id=null ] is not a known entity type. The compiler indicates the error in the line entityManager.persist(person); meaning person is not an instance of an entity class.



Now Let's see:

1. See that Person is an entity class which has an annotation @Entity that means we have declared this class as an entity class. If your entity class does not have @Entity annotation, this may be the cause of this error. In that case, add annotation @Entity in the entity class. In our case, though the entity class is annotated properly, other reasons may cause this error(see below).

2. As we are using Java Persistence API (JPA), we have a persistence.xml file containing the following xml code:
<?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="PersonPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/persondb"/>
      <property name="javax.persistence.jdbc.password" value="mypassword"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
    </properties>
  </persistence-unit>
</persistence>

We have error in this persistence.xml file. What's that? The persistence.xml must declare the entity class by writing <class>person.entity.Person</class>

So the correct persistence.xml will be:

<?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="PersonPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>person.entity.Person</class>    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/persondb"/>
      <property name="javax.persistence.jdbc.password" value="mypassword"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
    </properties>
  </persistence-unit>
</persistence>

If you use netbeans you can add the entity class declaration in the persistence.xml file very easily using the design view.
Read More

    email this       edit