Spring MVC – 24 – JPA/EclipseLink

Merhaba Arkadaslar
Bu bolumde Spring MVC ve JPA/EclipseLink entegrasyonunu gerceklestirecegiz.

Eger JPA/EclipseLink konusunda problemimiz varsa oncelikle ilgili yazi dizisine bakabilirsiniz.
Bununla birlikte Spring Core bolumunde JPA/EclipseLink ve Hibernate entegrasyonlarini yaptik.
Oncelikle bu entegrasyonu inceleyebilirsiniz.

JPA/EclipseLink yazi dizisi icin ;
EclipseLink/Hibernate JPA

Spring Core & JPA/Eclipselink implemantasyonu icin
Spring – 21 – JPA – 01
Spring – 22 – JPA – 02

Dependency

Oncelikle projemize JPA spect’i , EclipseLink reference implementation , Oracle icin gerekli dependency tanimlarini ekleyelim.
Oracle dependency i kullanabilmemiz icin ilgili reporistory de pom.xml dosyamiza eklememiz gerekli.

pom.xml

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

<properties>	
	....
	<jpa.version>2.1.1</jpa.version>
	<eclipselink.version>2.6.1</eclipselink.version>
	<oracle.version>11.2.0.3</oracle.version>
	<mysql.version>6.0.5</mysql.version>
</properties>

.....
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-orm</artifactId>
	<version>${spring.version}</version>
</dependency>


<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>javax.persistence</artifactId>
	<version>${jpa.version}</version>
</dependency>


<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>eclipselink</artifactId>
	<version>${eclipselink.version}</version>
</dependency>
....

Persistence Configuration

persistence.xml dosyamiz source folder altinda (bunun icin persistence isminde bir source folder olusturdum) META-INF altinda yer alacaktir. Icerigi hakkinda bilgiyi JPA bolumunde bulabilirsiniz.

persistence.xml

<?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="SpringJPA_Oracle_PU"
		transaction-type="RESOURCE_LOCAL">

		<class>_26.jpa.domain.Person</class>

		<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
		<!-- default persistence provider -->
		<properties>

			<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>

	<persistence-unit name="SpringJPA_MySQL_PU"
		transaction-type="RESOURCE_LOCAL">

		<class>_26.jpa.domain.Person</class>

		<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
		<!-- default persistence provider -->
		<properties>

			<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/springmvc.jpa.schema?serverTimezone=UTC" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<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>


</persistence>

Entity

Entity tanimimizi gerceklestirelim. Entity ve annotationlar hakkinda detayli bilgi icin JPA bolumunu inceleyebilirsiniz.

NOT : JPA implementation olarak EclipseLink kullandigimizda persistence.xml dosyamizda Entity tanimlarini eklemeyi unutmayalim.

<class>_26.jpa.domain.Person</class>

Person.java

package _26.jpa.domain;

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

@Entity
public class Person {

	@Id
	@GeneratedValue(strategy = GenerationType.TABLE)
	private int id;
	private String name;
	private String surname;
	private int salary;
	//getters and setters
	//
	public Person(String name, String surname, int salary) {
		super();
		this.name = name;
		this.surname = surname;
		this.salary = salary;
	}
	public Person() {
		super();
	}

	
}

Data Access Layer

Data Access Layer ‘da insert , update , delete ve read islemi icin metotlarimizi yazalim.

PersonDAO.java

package _26.jpa.dao;

import java.util.List;

import _26.jpa.domain.Person;

public interface PersonDAO {

	public void insertPerson(Person person);
	public Person getPersonById(int id);
	public List<Person> getAllPersons();
	public void updatePerson(Person person);
	public void deletePerson(int id);

}

PersonDAOImpl.java

package _26.jpa.dao;

import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import _26.jpa.domain.Person;

@Repository
public class PersonDAOImpl implements PersonDAO {

	private EntityManager entityManager;

	@Autowired
	public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
		entityManager = entityManagerFactory.createEntityManager();
	}

	@Override
	public void insertPerson(Person person) {
		entityManager.getTransaction().begin();
		entityManager.persist(person);
		entityManager.getTransaction().commit();
	}

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

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


	@Override
	public void updatePerson(Person person) {
		Person foundEmployee = getPersonById(person.getId());
		if(foundEmployee!=null){
			entityManager.getTransaction().begin();
			foundEmployee.setName(person.getName());
			foundEmployee.setSurname(person.getSurname());
			foundEmployee.setSalary(person.getSalary());
			entityManager.getTransaction().commit();
		}
	}

	@Override
	public void deletePerson(int id) {
		Person person = getPersonById(id);
		if (person != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(person);
			entityManager.getTransaction().commit();
		}

	}

}

EntityManager da yer alan persist metodu ile kayit ekleme islemi , remove metodu ile kayit silme islemi ve find metodu ile ilgili kaydi bulma islemini yapabiliyorduk.
Hatirlayacagimiz gibi insert , update ve delete islemi EntityTransaction arasinda olmasi gerekliydi.

NOT : Bu kisimlarda problem varsa JPA bolumune bakabilirsiniz.

Service Layer

Service Layer’i , Data Access Layer’a ulasmak icin kullanacagiz.

PersonService.java

package _26.jpa.service;

import java.util.List;

import _26.jpa.domain.Person;

public interface PersonService {

	public void insertPerson(Person person);
	public Person getPersonById(int id);
	public List<Person> getAllPersons();
	public void updatePerson(Person person);
	public void deletePerson(int id);
}

PersonServiceImpl.java

package _26.jpa.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import _26.jpa.dao.PersonDAOImpl;
import _26.jpa.domain.Person;

@Service
public class PersonServiceImpl implements PersonService {

	@Autowired
	private PersonDAOImpl personDAOImpl;

	public void insertPerson(Person person) {
		personDAOImpl.insertPerson(person);
	}

	public Person getPersonById(int id) {
		return personDAOImpl.getPersonById(id);
	}

	public List<Person> getAllPersons() {
		return personDAOImpl.getAllPersons();
	}

	public void updatePerson(Person person) {
		personDAOImpl.updatePerson(person);
	}

	public void deletePerson(int id) {
		personDAOImpl.deletePerson(id);
	}

	public Person createPerson(String name, String surname, int birthYear) {
		Person person = new Person(name, surname, birthYear);
		return person;
	}
}

Web Layer

Controller sinifimizi tanimlayalim.

  • getPersonList metodu ;
    PersonServiceImpl objesi uzerinden getAllPersons metodunu cagiriyoruz. Bu metot tum Person kayitlarini getirmektedir. Gelen bu listeyi attribute olarak ekliyoruz.
    Formumuzda @ModelAttribute u kullanacagiz bu nedenle yeni bir Person objesi olusturup ismi “newPerson” olacak sekilde ekliyoruz.
  • insertPerson metodu;
    Kayit ekledigimiz metodumuz , bind ettigimiz form alanlarini kullanarak yeni Person kaydini ekliyoruz. @ModelAttribute u ilgili yazida inceledik ;
    Spring MVC – 09 – Form Handling
  • deletePerson  metodu;
    Kayit sildigimiz metodumuz , ilgili kaydi unique id ye gore silebiliriz. Bu nedenle @RequestParam annotationdan yararlaniyoruz. Yine ilgili konuyu linkten inceleyebilirsiniz;
    Spring MVC – 09 – Form Handling
  • editPerson metodu;
    Kayit guncelledigimiz metod , ilgili kaydi unique id degerine gore guncelleyebiliriz. Bu nedenle @RequestParam annotationdan yararlaniyoruz. Guncelleyecegimiz kayda dair bilgileri forma getirmek icin getPersonById metodunu kullaniyoruz.
    Burada JSP dosyamizda buton ismini ve linkini dinamik sekilde ayarlamak icin ismi update olacak sekilde basit bir attribute ekliyorum.
  • updatePerson metodu ;
    Bu metotta guncelleme islemini yapiyoruz. HTTP Post ile gonderdigimiz form datasini kullanarak update query’imizi calistiriyoruz.
package _26.jpa.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import _26.jpa.domain.Person;
import _26.jpa.service.PersonServiceImpl;

@Controller
public class PersonController {

	@Autowired
	private PersonServiceImpl personServiceImpl;

	@RequestMapping(value = "/person.list", method = RequestMethod.GET)
	public String getPersonList(Model model) {
		
		System.out.println("...getPersonList...");
		
		List<Person> personList = personServiceImpl.getAllPersons();
		model.addAttribute("newPerson", new Person());
		model.addAttribute("allPersons", personList);
		
		return "26.jpa.view/personList";
	}

	@RequestMapping(value = "/person.add", method = RequestMethod.POST)
	public String addPerson(@ModelAttribute("newPerson") Person person, Model model) {
		
		System.out.println("...addPerson...");
		
		personServiceImpl.insertPerson(person);
		
		return "redirect:/person.list";
	}

	@RequestMapping(value = "/person.delete{personId}", method = RequestMethod.GET)
	public String deletePerson(@RequestParam("personId") int id) {
		
		System.out.println("...deletePerson...");
		
		personServiceImpl.deletePerson(id);
		
		return "redirect:/person.list";
	}

	@RequestMapping(value = "/person.edit{personId}", method = RequestMethod.GET)
	public String editPerson(@RequestParam("personId") int id, Model model) {
		
		System.out.println("...editPerson ...");
		
		model.addAttribute("newPerson", personServiceImpl.getPersonById(id));
		model.addAttribute("allPersons", personServiceImpl.getAllPersons());
		model.addAttribute("update", "update");
		
		return "26.jpa.view/personList";
	}

	@RequestMapping(value = "/person.update", method = RequestMethod.POST)
	public String updatePerson(@ModelAttribute("newPerson") Person person, Model model) {
	
		System.out.println("...update person...");
		
		personServiceImpl.updatePerson(person);
		
		return "redirect:/person.list";
	}

}

View Layer

Su ornekte kullandigim JSP sayfasini biraz daha gelistirip burada kullanalim.
EclipseLink – 16 – Servlet & JSP & JPA & Bootstrap

personList.jsp

NOT : Gerekli aciklamalari JSP sayfasinda ilgili yerde bulabilirsiniz.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!-- JSTL ve Spring form tagini ekleylelim.. -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"  %>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>person</title>

<!-- bootstrap ve jqery icin js ve css ekleme islemi.. -->

<link rel="stylesheet" type="text/css" media="screen" href="<c:url value="/resources/css/bootstrap.min.css" />" />
<script src="<c:url value="/resources/js/bootstrap.min.js" />"></script>
<script src="<c:url value="/resources/js/jquery.min.js" />"></script>

</head>
<body>


<!-- butonun ismini ve url adresini dinamaik olarak degistirmek icin! -->

<c:url var="actionURL" value="/person.add"/>
<c:set var="buttonName" value="add"/>
<c:if test="${ !empty update}">
<c:url var="actionURL" value="/person.update"/>
<c:set var="buttonName" value="update"/>
</c:if>

<!-- http://www.layoutit.com/
https://datatables.net/examples/styling/bootstrap.html
-->

<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-6">

<!-- modelAttribute , form data bind  -->
<!-- newPerson ismi ile Controller'daki newPerson attribute isminin ayni olduguna dikkat edelim!  -->
<form:form  modelAttribute="newPerson" class="form-horizontal" method="post" action="${actionURL}">
<fieldset>

	<!-- Form Name -->
	<legend>Person Add</legend>

	<!-- Text input-->
	<div class="form-group">
		<label class="col-md-4 control-label" for="name">Name</label>
		<div class="col-md-4">		
			<!-- update isleminde kullanmak icin hidden olarak id ! -->								
			<form:hidden path="id" />
			<form:input id="name" path="name" type="text" class="form-control input-md"/>
		</div>
	</div>

	<!-- Text input-->
	<div class="form-group">
		<label class="col-md-4 control-label" for="surname">Surname</label>
		<div class="col-md-4">
			<form:input id="surname" path="surname" type="text" class="form-control input-md"/>
		</div>
	</div>

	<!-- Text input-->
	<div class="form-group">
		<label class="col-md-4 control-label" for="salary">Salary</label>
		<div class="col-md-4">
			<form:input id="salary" path="salary" type="number" class="form-control input-md"/>
		</div>
	</div>

	<!-- Button -->
	<div class="form-group">
		<label class="col-md-4 control-label" for="add"></label>
		<div class="col-md-4">
			<input type="submit" id="btnAdd" class="btn btn-primary" value ="${buttonName}"/>
		</div>
	</div>

</fieldset>
</form:form>
</div>
<div class="col-md-6"></div>
</div>

<div class="row">
<div class="col-md-6">
<legend>Person List</legend>
<table id="example" class="table table-striped table-bordered"
cellspacing="0" width="100%">
<thead>
	<tr>
		<th>Id</th>
		<th>Name</th>
		<th>Surname</th>
		<th>Salary</th>
		<th>Action</th>
	</tr>
</thead>
<tbody>

<!-- Kayitlari listeleyelim... -->
	<c:forEach items="${allPersons}" var="person">
		<tr>
			<td><c:out value="${person.id}" /></td>
			<td><c:out value="${person.name}" /></td>
			<td><c:out value="${person.surname}" /></td>
			<td><c:out value="${person.salary}" /></td>
		<!-- Delete islemi icin RequestParam ekleyelim... -->	
			<td colspan="2"><a href="person.delete?personId=${person.id}"
				class="btn btn-danger" type="button">Delete</a>
		<!-- edit islemi icin RequestParam ekleyelim... -->			
				<a href="person.edit?personId=${person.id}"
				class="btn btn-warning" type="button">Edit</a>
				
				</td>									    
		</tr>
	</c:forEach>
</tbody>
</table>
</div>
<div class="col-md-6"></div>
</div>
</div>
</div>
</div>

</body>
</html>

XML Configuration

26.jpa.xml
bean tanimi olarak org.springframework.orm.jpa.LocalEntityManagerFactoryBean sinifini kullaniyoruz. persistenceUnitName property olarak SpringJPA_PU degerini verdik. Bu bilgi persistence.xml dosyamizdaki Persistence Unit bilgisine karsilik gelmektedir.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<mvc:resources mapping="/resources/**" location="/resources/" />
	<mvc:annotation-driven />
		
	<context:component-scan base-package="_26" />
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	
	<bean id="entityManagerFactoryId"
		class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="SpringJPA_PU"></property>
	</bean>
		

</beans>

web.xml

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>

<init-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>					
	<!-- 		
		 /WEB-INF/01.appContext.xml
		 ...
	-->
	 /WEB-INF/26.jpa.xml			   						  					
	</param-value> 			
 </init-param>	
<load-on-startup>1</load-on-startup>
</servlet>

Run Application

Ornegimizi calistiralim ;

http://localhost:8080/injavawetrust.springmvc/person.list

person 1

Formu doldurup “add” butonuna tikladigimizda ;

person 2

Ilgili kayit eklendi. Edit butonuna tikladigimizda , ilgili kayda ait bilgiler form alanina gelecektir. Buton ismi “update” olarak degisti. Bu kadar kod sonrasi bir maas zammini hak ettim 🙂

person 3

Salary bilgisini 2000 yapip “update” dedigimde ;

person 4

Son olarak “Delete” butonuna basip ilgili kaydi silebiliriz. Birden fazla kayit ekleyip guncelleme ve silme islemlerini test edebiliriz.

Github kaynak kodlar / source folder
Injavawetrust-springmvc-tutorial

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. Required fields are marked *