EclipseLink – 17 – JSF & JPA

Merhaba Arkadaslar
Onceki bolumde Servlet&JSP ile JPA entegrasyonu gerceklestirmistik. Bu bolumde JSF ve JPA entegrasyonunu yapacagiz.

Burada JSF ile ilgili detayli olarak bilgi vermeyecegim.
JSF (Java Server Faces ) ile ilgili bilgileri surada bulabilirsiniz ; JSF

Dynamic Web Project & pom.xml

Oncelikle Eclipste yeni bir Dynamic Web Project olusturalim daha sonrasinda Maven projesine donusturelim.

pom.xml dosyamiza ekleyecegimiz dependency tanimlari ;

  • JSF ve JSF Impl jarlari
  • JPA ve EclipseLink jarlari
  • Oracle/MySQL jarlari

pom.xml

	<repositories>
		<repository>
			<id>codelds</id>
			<url>https://code.lds.org/nexus/content/groups/main-repo</url>
		</repository>
	</repositories>

	<dependencies>

		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.2.11</version>
		</dependency>
		
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.2.11</version>
		</dependency>

		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>eclipselink</artifactId>
			<version>2.6.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>
		
	</dependencies>

Entity/Model

Entity/Model sinifimiz onceki ornegimizde oldugu gibi Employee ;

Employee.java

package model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.TABLE)
	private int id;
	private String name;
	private String surname;
	private int salary;

	Employee() {
		super();
	}

	public Employee(String name, String surname, int salary) {
		super();
		this.name = name;
		this.surname = surname;
		this.salary = salary;
	}

	//getters and setters
	...

}

persistence.xml

persistence.xml dosyamiz source folder’da META-INF klasorunda olmalidir. Bunun icin yeni bir source folder olusturdum.

persistence.xml
Onceki orneklerde kullandigimiz persistence.xml dosyasini burada da kullandim.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="EmployeePersistenceUnit"
	transaction-type="RESOURCE_LOCAL">
			
	<class>model.Employee</class>
	<properties>			
		<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
		<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa.schema" />
		<property name="javax.persistence.jdbc.user" value="root" />
		<property name="javax.persistence.jdbc.password" value="123456" />
		
		<!-- 			
		<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
		<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe" />
		<property name="javax.persistence.jdbc.user" value="Levent" />
		<property name="javax.persistence.jdbc.password" value="123456" />
			-->			
		<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
		<property name="eclipselink.logging.level" value="OFF" />				
	</properties>
</persistence-unit>

Data Layer

Onceki ornegimizdeki Data Layer katmanini burada aynen kullaniyorum. Employee.java

package dao;

import java.util.List;

import model.Employee;

public interface EmployeeDAO {

	public Employee insertEmployee(Employee employee);

	public Employee findEmployee(int id);

	public List<Employee> findAllEmployees();

	public void removeEmployee(int id);
}

EmployeeDAOImpl.java

package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;

import utility.EntityManagerUtility;
import model.Employee;

public class EmployeeDAOImpl implements EmployeeDAO {

	private EntityManager entityManager;

	public EmployeeDAOImpl() {
		EntityManagerFactory entityManagerFactory = EntityManagerUtility.getEntityManagerFactory();
		entityManager = entityManagerFactory.createEntityManager();
	}

	@Override
	public Employee insertEmployee(Employee employee) {
		entityManager.getTransaction().begin();
		entityManager.persist(employee);
		entityManager.getTransaction().commit();
		return employee;
	}

	@Override
	public Employee findEmployee(int id) {
		return entityManager.find(Employee.class, id);
	}

	@Override
	public List<Employee> findAllEmployees() {
		TypedQuery<Employee> query = entityManager.createQuery("Select e from Employee e", Employee.class);
		return query.getResultList();

	}

	@Override
	public void removeEmployee(int id) {
		Employee employee = findEmployee(id);
		if (employee != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(employee);
			entityManager.getTransaction().commit();
		}
	}
}

Service Layer

Data Layer ‘a direkt erisim yerime Service Layer’i kullaniyoruz.

EmployeeServiceImpl.java

package service;

import java.util.List;

import model.Employee;
import dao.EmployeeDAOImpl;

public class EmployeeServiceImpl implements EmployeeService {

	private EmployeeDAOImpl employeeDAOImpl;

	public EmployeeServiceImpl() {
		employeeDAOImpl = new EmployeeDAOImpl();
	}

	private EmployeeDAOImpl getEmployeeDAOImpl() {
		return employeeDAOImpl;
	}

	@Override
	public Employee insertEmployee(Employee employee) {
		return getEmployeeDAOImpl().insertEmployee(employee);
	}

	@Override
	public Employee findEmployee(int id) {
		return getEmployeeDAOImpl().findEmployee(id);
	}

	@Override
	public List<Employee> findAllEmployees() {
		return getEmployeeDAOImpl().findAllEmployees();
	}

	@Override
	public void removeEmployee(int id) {
		getEmployeeDAOImpl().removeEmployee(id);
	}
}

EntityManagerUtility

EntityManagerUtility.java

package utility;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerUtility {

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

	public static EntityManagerFactory getEntityManagerFactory() {
		return entityManagerFactory;
	}

}

ManagedBean / Controller

Simdi de JSF ManagedBean’inimizi yazalim. Burada kullanacagimiz Managed Bean , JSF Datatable orneginde kullandigim yapiya benzer sekilde olacak.
Yeni kayit eklemek ve kayit silmek icin addEmployee ve deleteEmployee metodu tanimladik.
Bu metotlardan Service Layer’a ulasiyoruz , Service Layer’da Data Layer’a erisiyor ve kayit ekleme/silme ve tum kayitlarin getirilmesi islemini gerceklestirmektedir.

package controller;

import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import service.EmployeeService;
import service.EmployeeServiceImpl;
import model.Employee;

@ManagedBean
@SessionScoped
public class EmployeeController {

	private String name;
	private String surname;
	private int salary;
	private List<Employee> employees = new ArrayList<Employee>();

	public String getName() {
		return name;
	}

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

	public String getSurname() {
		return surname;
	}

	public void setSurname(String surname) {
		this.surname = surname;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public List<Employee> getEmployees() {
		return employees;
	}
	
	
	public void addEmployee() {

		EmployeeService employeeService = new EmployeeServiceImpl();
		Employee employee = new Employee(name,surname,salary);
		employeeService.insertEmployee(employee);
		
		employees = employeeService.findAllEmployees();

	}

	public void deleteEmployee(int id) {
		EmployeeService employeeService = new EmployeeServiceImpl();
		employeeService.removeEmployee(id);

		employees = employeeService.findAllEmployees();

	}
}

View

xhtml sayfamizda h:dataTable component’ini kullanacagiz. JSF yazilarimda Data table bolumunde kullandigim xhtml sayfasinda ufak degisiklikler yaparak burada aynen kullaniyorum.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
	<h:outputStylesheet library="css" name="table-style.css" />
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>JSF &amp; JPA</title>
</h:head>
<h:body>

	<h:form id="form">

		<h:dataTable id="dataTable" value="#{employeeController.employees}" var="myEmployee"
			captionStyle="font-size:20px" styleClass="employee-table"
			headerClass="employee-table-header"
			rowClasses="employee-table-oddRow,employee-table-evenRow">

			<f:facet name="caption">Employee List</f:facet>

			<h:column>
				<f:facet name="header">Name</f:facet>
				#{myEmployee.name}
			</h:column>

			<h:column>
				<f:facet name="header">Surname</f:facet>
				#{myEmployee.surname}	
			</h:column>

			<h:column>
				<f:facet name="header">Salary</f:facet>
				#{myEmployee.salary}
			</h:column>
			
			<h:column>
				<f:facet name="header">Delete</f:facet>				
				<h:commandLink value="Delete" action="#{employeeController.deleteEmployee(myEmployee.id)}" />
			</h:column>

		</h:dataTable>

		<h3>Add employee</h3>
		<table id="myTable">
			<tr>
				<td>Name:</td>
				<td><h:inputText id="name" value="#{employeeController.name}" /></td>
			</tr>
			<tr>
				<td>Surname:</td>
				<td><h:inputText  id="surname" value="#{employeeController.surname}" /></td>
			</tr>
			<tr>
				<td>Salary:</td>
				<td><h:inputText value="#{employeeController.salary}" /></td>
			</tr>
		</table>
		<p>
			<h:commandButton value="Add" action="#{employeeController.addEmployee}"/>				
		</p>
	</h:form>

</h:body>
</html>

Ornegimizi calistiralim , Add ve delete islemlerini test edelim.

employee table jpa jsf

Her sey yolunda kayitlar eklendi ve silebiliyoruz. Tablomuzu inceledigimzde ;

employee jpa jsf

Kaynak kodlar : injavawetrust.jsfAndJpa

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published.