JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Sample Application for Java Persistence API (JPA)

April 15, 2007 by Krishna Srinivasan Leave a Comment

This article is the last part of the article series Java Persistence API (JPA), the earlier articles are introduction to JPA and the query api in JPA. This article is only for explaining the sample program with concepts used in the previous articles. I would recommend reading the previous two articles before start analyzing this sample code. If you are familiar with the JPA concepts, you can jump into the code and complete reading this article. If you have any doubts or queries, please post it in the comments section. Thank you for reading our blog. Have a fun!!

Following is a sample code in J2SE that creates and find Employee objects.

Code for Employee.java

[code lang=”java”]package com.javabeat.ejb30.persistence.entities;

import java.io.Serializable;
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;

@Entity(name = "EMPLOYEE")

@NamedQueries({
@NamedQuery(name = "Employee.findAll",
query = "SELECT EMP FROM EMPLOYEE AS EMP")
})

public class Employee implements Serializable {

@Column(name = "EMP_NAME", nullable = false, length = 100)
private String name;

@Column(name = "EMP_AGE", nullable = true)
private int age;

@Column(name = "EMP_SALARY", nullable = true)
private double salary;

@Id
@Column(name = "EMP_ID", nullable = false)
private Long id;

public Employee() {
}

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public int getAge(){
return age;
}

public void setAge(int age){
this.age = age;
}

public double getSalary(){
return salary;
}

public void setSalary(double salary){
this.salary = salary;
}
public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}
}[/code]

The following code test the Employee entity class by creating some sample employee objects and then finding them using the Query API.

Code for EmployeeTest.java:

[code lang=”java”]package employee.test;

import com.javabeat.ejb30.persistence.entities.Employee;
import java.util.Arrays;
import java.util.List;
import javax.naming.Name;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class EmployeeTest {

private static EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("EmployeePersistentUnit");

private EntityManager entityManager;

public EmployeeTest() {
entityManager = entityManagerFactory.createEntityManager();
}

public void createEmployees(){
try{
beginTransaction();
Employee emp1 = createEmployee("Johny", 35, 10000, 1L);
entityManager.persist(emp1);
Employee emp2 = createEmployee("David", 43, 50000, 2L);
entityManager.persist(emp2);
Employee emp3 = createEmployee("Philip", 55, 70000, 3L);
entityManager.persist(emp3);
Employee emp4 = createEmployee("James", 29, 30000, 4L);
entityManager.persist(emp4);
}catch (Exception exception){
failTransaction();
}finally{
commitTransaction();
}
}

public List findAllEmployees(){
Query query = entityManager.createNamedQuery("Employee.findAll");
List employees = query.getResultList();
return ((List)employees);
}

public Employee findByName(String empName){
String queryString =
"SELECT EMP FROM EMPLOYEE AS EMP WHERE EMP.EMP_NAME = ?1";
Query query = entityManager.createQuery(queryString);
query.setParameter(1, empName);
return (Employee)query.getSingleResult();
}

public void display(List employees){
for(Employee employee : employees){
display(employee);
}
}

private void display(Employee employee){
StringBuilder results = new StringBuilder();
results.append("Name = " + employee.getName() + ", Age = "
+ employee.getAge() + ", ");
results.append("Salary = " + employee.getSalary() + ",
Id = " + employee.getId());
System.out.println(results.toString());
}

private void beginTransaction(){
entityManager.getTransaction().begin();
}

private void commitTransaction(){
entityManager.getTransaction().commit();
}

private void failTransaction(){
entityManager.getTransaction().rollback();
}

private Employee createEmployee(String name, int age,
double salary, long primaryKey){
Employee employee = new Employee();
employee.setName(name);
employee.setAge(age);
employee.setSalary(salary);
employee.setId(primaryKey);
return employee;
}
}[/code]

For the above code to work, we have to create a persistence.xml file that contains the configurations for the EntityManager object like the database name, its URL, username/password etc inside the META-INF directory. Since it is a J2SE application we have to declare the type of transaction as Resource-Local. The following is the persistence.xml

Persistence.xml file:

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<persistence-unit name="EmployeePersistentUnit"
transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.
ejb.cmp3.EntityManagerFactoryProvider</provide>
<class>
com.javabeat.ejb30.persistence.entities.Employee
</class>
<properties>
vproperty
name="toplink.jdbc.url" value="jdbc:derby://localhost:1527/sample"/>
<property
name="toplink.jdbc.user" value="app"/>
<property
name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="toplink.jdbc.password" value="app"/>
<property name="toplink.ddl-generation"
value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>[/code]

The above example uses the apache derby database for persisting the Employee objects as represented by the provider tag.

also read:

  • Introduction to JPA
  • The query api in JPA.

Filed Under: Java EE Tagged With: EJB, JPA

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved