Persistence with Java SE an example


1. Create a Entity Class {Employee.java}

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

@Entity // Make Employee Class into an entity by annotate the class with @Entity.
public class Employee {
@Id private int id; //property that holds the persistent identity of the entity (the primary key).
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; }

2. Creating Entity Manager {EmployeeService.java}

import javax.persistence.*;
import java.util.Collection;

public class EmployeeService {

protected EntityManager em;

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

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

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

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

public Employee findEmployee(long id) {

return em.find(Employee.class, id);
}

public Collection findAllEmployees() {
Query query = em.createQuery("SELECT e FROM Employee e");
return (Collection) query.getResultList();
}
}

3. Creating a test Class to test Persistence {EmployeeTest.java}

import javax.persistence.*;
import java.util.Collection;
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(164, "Shishir", 120000);
em.getTransaction().commit();
System.out.println("Persisted " + emp);

// find a specific employee
Employee emp = service.findEmployee(158);
System.out.println("Found " + emp);
jLabel1.setText(emp.toString());

// find all employees
Collection emps = service.findAllEmployees();
for (Employee e : emps)
System.out.println("Found employee: " + e);

// close the EM and EMF when done
em.close();
emf.close();
}

, , ,

Comments are closed.