Personal notes on Java
For other technologies like HTML, CSS, .NET, PHP, etc. check my other blog

You can use JPA in JavaSE almost the same way has you use it in JavaEE.
Some diferences are:

  • In JavaSE, you don't get an EntityManager instance from the Application Server (there isn't one!) so you have to create a new instance yourself, ex:
    EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("EmployeeServicePU");
    EntityManager em = emf.createEntityManager();
  • In JavaSE you cant use the container managed transactions like JTA (there is no Application Server!) so you have to do it manually.
    You can use the EntityTransaction service for this, ex:
    em.getTransaction().begin();
    createEmployee(158, "John Doe", 45000);
    em.getTransaction().commit();
  • In JavaSE you need to specify every Entity class in the Persistence Unit definition (in persistence.xml);
    I.e. define XML <class> elements like the "myentities.Employee" class below:
      <persistence-unit name="JPAJavaSEPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>myentities.Employee</class>
        <properties>

Steps to take:
  1. Create a normal JavaSE project;
     
  2. Add the jar that contains the javax.persistence package into your project libraries.
    If you are using Glassfish you can find it on the installation folder.
    Ex.: C:\glassfish3\glassfish\modules\javax.persistence.jar
     
  3. Create a normal class and turn it into an entity:
     - Annotate your class with @Entity;
     - Annotate a class field with @Id;
     - Create get/set methods to the id field to turn in into a property;
     - The class must implement Serializable;
    Ex.:
    @Entity
    public class Employee implements Serializable {
    
        @Id 
     private int id;
        private String name;
        private long salary;  
     ...
    } 
    
      
  4. Create the database on your DBMS
    For example, if you are using MySQL you can use "MySQL Workbench" to create the database schema.
    In this example I've created a database with this attributes:
     - database name: "jpa_javase"
     - user/pass: "root" "1234";
     - MySQL is running on localhost and listening on port  3306 (the default port);
     
  5. Create a persistence unit (PU) and add the the JPA implementation jars into your project libraries:
    If you are using Netbeans you can click on the light bulb next to the class name and it will take you through the entire configuration of the PU and the connection that it uses for the database.


    This will:
    • Generate the necessary xml definitions for the PU in your projects persistence.xml file.
      Example of the persistence.xml file:
      <?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="JPAJavaSEPU" transaction-type="RESOURCE_LOCAL">
          <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
          <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_javase"/>
            <property name="javax.persistence.jdbc.password" value="1234"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
          </properties>
        </persistence-unit>
      </persistence>
    • Add the jars of your JPA implementation (ex. Hibernate; EclipseLink, etc.) into your project libraries.
      For the EclipseLink it would import these 2 jars:
      TODO

  6. Create a test method to run a JPA instruction and check if everything is ok
    Ex.:
    public static void main(String[] args) {
     try {
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAJavaSEPU");
      EntityManager em = emf.createEntityManager();
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Antero");
      employee.setSalary(3000);
      
      em.getTransaction().begin();
      em.persist(employee);
      em.getTransaction().commit();
     } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
     }
    } 
    
     
    NOTE: you need to surround em.persist with the em.getTransaction().begin() and em.getTransaction().commit() to start and end a transaction otherwise nothing will get persisted on the database!
     
  7. Add your "DBMS JDBC driver" jar into your project libraries
    For MySQL this driver is called "Connector/J".
    The file name is something like "mysql-connector-java-5.1.21-bin.jar" depending on your version of the driver.
    I've mine in: C:\glassfish3\glassfish\domains\domain1\lib\mysql-connector-java-5.1.21-bin.jar
    If you don't have it yet check the JDBC page on this site to see where to find it and download it.

    If you skip this step and run the program you'll get and error like:
    ...
    Exception Description: Configuration error.  Class [com.mysql.jdbc.Driver] not found.
    ... 
    
     
  8. Add your entity classes into the Persistence Unit (PU) configuration (persistence.xml)
    • You can add them manually in the persistence.xml
      For example for the entity "Employee" you would add a line like:
      <class>entities.Employee</class>
      
      Where "entities" is the package name for the "Employee" class.
    • Or you can use "NetBeans XML editor" to edit the persistence.xml and add the entities through the GUI:
      Double click "persistence.xml" on the project tree to open the XML editor. Then click the "Add Class..." button to select and add the entities;

    If you skip this step you'll get an error like:
    Error: Object: entities.Employee@1aa8d4 is not a known entity type.
    


Code example

Employee entity class
@Entity
public class Employee {
@Id private int id;
private String name;
private long salary;
public Employee() {}
public Employee(int id) { this.id = id; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public long getSalary() { return salary; }
public void setSalary (long salary) { this.salary = salary; }
}

Service Class for Operating on Employee Entities:
import javax.persistence.*;
import java.util.List;

public class EmployeeService {

    protected EntityManager em;

    public EmployeeService(EntityManager em) {
        this.em = em;
    }

    public Employee createEmployee(int id, String name, long salary) {
        Employee emp = new Employee(id);
        emp.setName(name);
        emp.setSalary(salary);
        em.persist(emp);
        return emp;
    }

    public void removeEmployee(int id) {
        Employee emp = findEmployee(id);
        if (emp != null) {
            em.remove(emp);
        }
    }

    public Employee raiseEmployeeSalary(int id, long raise) {
        Employee emp = em.find(Employee.class, id);
        if (emp != null) {
            emp.setSalary(emp.getSalary() + raise);
        }
        return emp;
    }

    public Employee findEmployee(int id) {
        return em.find(Employee.class, id);
    }

    public List<Employee> findAllEmployees() {
        TypedQuery<Employee> query = em.createQuery(
                "SELECT e FROM Employee e", Employee.class);
        return query.getResultList();
    }
}



Using EmployeeService
import javax.persistence.*;
import java.util.List;

public class EmployeeTest {

    public static void main(String[] args) {
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("EmployeeService");
        EntityManager em = emf.createEntityManager();
        EmployeeService service = new EmployeeService(em);
// create and persist an employee
        em.getTransaction().begin();
        Employee emp = service.createEmployee(158, "John Doe", 45000);
        em.getTransaction().commit();
        System.out.println("Persisted " + emp);
// find a specific employee
        emp = service.findEmployee(158);
        System.out.println("Found " + emp);
// find all employees
        List<Employee> emps = service.findAllEmployees();
        for (Employee e : emps) {
            System.out.println("Found employee: " + e);
        }
// update the employee
        em.getTransaction().begin();
        emp = service.raiseEmployeeSalary(158, 1000);
        em.getTransaction().commit();
        System.out.println("Updated " + emp);
// remove an employee
        em.getTransaction().begin();
        service.removeEmployee(158);
        em.getTransaction().commit();
        System.out.println("Removed Employee 158");
// close the EM and EMF when done
        em.close();
        emf.close();
    }
}

Sem comentários:

Enviar um comentário