Tuesday 2 July 2019

JPA: Entity class


Entity is the basic programming artifact in JPA. It is a lightweight persistent domain object.

How to create an entity class?
An entity class can be created in two ways.
         a. By using @Entity annotation
         b. Using XML configuration
        
Let me explain, how to create an entity class using @Entity annotation and insert the object of Entity class into table.

Employee.java
package com.smaple.entities;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {

 @Id
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int 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;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


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="myPersistenceUnit"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

  <class>com.sample.myApp.entities.Employee</class>

  <properties>
   <property name="eclipselink.target-database" value="Derby" />
   <property name="javax.persistence.jdbc.driver"
    value="org.apache.derby.jdbc.ClientDriver" />
   <property name="javax.persistence.jdbc.url"
    value="jdbc:derby://localhost:1527/demoDatabase;create=true" />
   <property name="javax.persistence.jdbc.user" value="APP" />
   <property name="javax.persistence.jdbc.password" value="APP" />
   <property name="eclipselink.logging.level" value="INFO" />

   <property name="eclipselink.ddl-generation"
    value="drop-and-create-tables" />

   <property name="eclipselink.ddl-generation.output-mode"
    value="database" />
  </properties>

 </persistence-unit>
</persistence>


TestApp.java
package com.sample.myApp;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.sample.myApp.entities.Employee;

public class TestApp {

 public static void main(String args[]) {
  EntityManagerFactory emf = null;
  EntityManager em = null;

  try {
   emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

   em = emf.createEntityManager();

   Employee emp = new Employee();
   emp.setFirstName("Krishna");
   emp.setLastName("Gurram");
   emp.setId(1);

   em.getTransaction().begin();
   em.persist(emp);
   em.getTransaction().commit();

   Query q = em.createQuery("select e from Employee e", Employee.class);
   List<Employee> emps = q.getResultList();
   for (Employee emp1 : emps) {
    System.out.println(emp1);
   }
  } finally {
   if (em != null && em.isOpen()) {
    em.close();
   }

   if (emf != null && emf.isOpen()) {
    emf.close();
   }
  }

 }

}


Project structure looks like below.


Run TestApp.java, you can able to see below messages in the console.

[EL Info]: 2018-06-25 08:59:41.644--ServerSession(707976812)--EclipseLink, version: Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f
[EL Info]: connection: 2018-06-25 08:59:41.766--ServerSession(707976812)--/file:/C:/Users/Krishna/java9/jpaDemo/target/classes/_myPersistenceUnit login successful
Employee [id=1, firstName=Krishna, lastName=Gurram]
[EL Info]: connection: 2018-06-25 08:59:42.13--ServerSession(707976812)--/file:/C:/Users/Krishna/java9/jpaDemo/target/classes/_myPersistenceUnit logout successful

Points to note
a. Entity class must have a no-arg default constructor. 
For example, I updated Employee.java and TestApp.java classes like below.


Employee.java
package com.sample.myApp.entities;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {

 public Employee(int id, String firstName, String lastName) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 @Id
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int 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;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


TestApp.java
package com.sample.myApp;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.sample.myApp.entities.Employee;

public class TestApp {

 public static void main(String args[]) {
  EntityManagerFactory emf = null;
  EntityManager em = null;

  try {
   emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

   em = emf.createEntityManager();

   Employee emp = new Employee(1, "Krishna", "Gurram");

   em.getTransaction().begin();
   em.persist(emp);
   em.getTransaction().commit();

   Query q = em.createQuery("select e from Employee e", Employee.class);
   List<Employee> emps = q.getResultList();
   for (Employee emp1 : emps) {
    System.out.println(emp1);
   }
  } finally {
   if (em != null && em.isOpen()) {
    em.close();
   }

   if (emf != null && emf.isOpen()) {
    emf.close();
   }
  }

 }

}


When I ran TestApp.java, I end up in below errors.

[EL Info]: 2018-06-25 09:01:45.574--ServerSession(707976812)--EclipseLink, version: Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f
[EL Severe]: 2018-06-25 09:01:45.711--ServerSession(707976812)--Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions: 
---------------------------------------------------------

Exception [EclipseLink-63] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The instance creation method [com.sample.myApp.entities.Employee.<Default Constructor>], with no parameters, does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: com.sample.myApp.entities.Employee.<init>()
Descriptor: RelationalDescriptor(com.sample.myApp.entities.Employee --> [DatabaseTable(EMPLOYEE)])

Runtime Exceptions: 
---------------------------------------------------------

[EL Info]: connection: 2018-06-25 09:01:45.716--ServerSession(707976812)--/file:/C:/Users/Krishna/java9/jpaDemo/target/classes/_myPersistenceUnit logout successful
[EL Severe]: ejb: 2018-06-25 09:01:45.716--ServerSession(707976812)--Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions: 
---------------------------------------------------------

Exception [EclipseLink-63] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The instance creation method [com.sample.myApp.entities.Employee.<Default Constructor>], with no parameters, does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: com.sample.myApp.entities.Employee.<init>()
Descriptor: RelationalDescriptor(com.sample.myApp.entities.Employee --> [DatabaseTable(EMPLOYEE)])

Runtime Exceptions: 
---------------------------------------------------------

Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [myPersistenceUnit] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions: 
---------------------------------------------------------

Exception [EclipseLink-63] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The instance creation method [com.sample.myApp.entities.Employee.<Default Constructor>], with no parameters, does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: com.sample.myApp.entities.Employee.<init>()
Descriptor: RelationalDescriptor(com.sample.myApp.entities.Employee --> [DatabaseTable(EMPLOYEE)])

Runtime Exceptions: 
---------------------------------------------------------

 at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:900)
 at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:840)
 at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:216)
 at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:324)
 at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:348)
 at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:311)
 at com.sample.myApp.TestApp.main(TestApp.java:21)
Caused by: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [myPersistenceUnit] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions: 
---------------------------------------------------------

Exception [EclipseLink-63] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The instance creation method [com.sample.myApp.entities.Employee.<Default Constructor>], with no parameters, does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: com.sample.myApp.entities.Employee.<init>()
Descriptor: RelationalDescriptor(com.sample.myApp.entities.Employee --> [DatabaseTable(EMPLOYEE)])

Runtime Exceptions: 
---------------------------------------------------------

 at org.eclipse.persistence.exceptions.EntityManagerSetupException.deployFailed(EntityManagerSetupException.java:239)
 ... 7 more
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions: 
---------------------------------------------------------

Exception [EclipseLink-63] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The instance creation method [com.sample.myApp.entities.Employee.<Default Constructor>], with no parameters, does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: com.sample.myApp.entities.Employee.<init>()
Descriptor: RelationalDescriptor(com.sample.myApp.entities.Employee --> [DatabaseTable(EMPLOYEE)])

Runtime Exceptions: 
---------------------------------------------------------

 at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:757)
 at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:693)
 at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:624)
 at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.postConnectDatasource(DatabaseSessionImpl.java:863)
 at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.login(DatabaseSessionImpl.java:820)
 at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:256)
 at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:759)
 ... 5 more

b. The no-arg constructor must be public or protected.

c. An enum or interface must not be designated as an entity.

d. The entity class must not be final.

e. No methods or persistent instance variables of the entity class may be final.

f. Entities support inheritance.
g. An abstract class can be an entity


h. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.


Previous                                                    Next                                                    Home

No comments:

Post a Comment