Spring MVC – 25 – Hibernate

Merhaba Arkadaslar
Onceki bolumde Spring MVC & JPA (EclipseLink) entegrasyonunu gerceklestirdik.
Bu bolumde ise Spring MVC & Hibernate entegrasyonunu gerceklestirecegiz.

Dependency

Oncelikle pom.xml dosyamiza hibernate dependency tanimini ekleyelim.

pom.xml

<properties>
	...
	<hibernate.version>5.2.6.Final</hibernate.version>
	..
</properties>


<!-- EclipseLink dependency -->
<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink -->
<!-- disable when using hibernate -->
<!-- 
<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>eclipselink</artifactId>
	<version>${eclipselink.version}</version>
</dependency>
 -->

<!-- hibernate dependency -->
<!-- disable when using JPA -->
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>${hibernate.version}</version>
</dependency>
	

Entity

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

EclipseLink/Hibernate JPA

Person.java

package _27.hibernate.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 _27.hibernate.dao;

import java.util.List;

import _27.hibernate.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 _27.hibernate.dao;

import java.util.List;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import _27.hibernate.domain.Person;

@Repository
public class PersonDAOImpl implements PersonDAO {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void insertPerson(Person person) {
		Session session = getCurrentSession();
		session.persist(person);
	}

	@Override
	public Person getPersonById(int id) {
		Session session = getCurrentSession();
		Person person = session.get(Person.class, id);
		return person;
	}

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

	@Override
	public void updatePerson(Person person) {
		Session session = getCurrentSession();
		session.update(person);
	}

	@Override
	public void deletePerson(int id) {
		Session session = getCurrentSession();
		Person p = (Person) session.get(Person.class, new Integer(id));
		System.out.println(p);
		if (p != null) {
			session.delete(p);
		}

	}

}

Service

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

PersonService.java

package _27.hibernate.service;

import java.util.List;
import _27.hibernate.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
Service Layer’da @Transactional annotation i ekliyoruz. Boylece declarative transaction yonetimini gerceklestiriyoruz.
Spring – 26 – Declarative Transaction

package _27.hibernate.service;

import java.util.List;

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

import _27.hibernate.dao.PersonDAOImpl;
import _27.hibernate.domain.Person;

@Service
public class PersonServiceImpl implements PersonService {

	@Autowired
	private PersonDAOImpl personDAOImpl;

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

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

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

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

	@Override
	@Transactional
	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;
	}
}

XML Configuration

Oncelikle ilgili namespace tanimlamalarini ekleyelim ;
xmlns:tx=”http://www.springframework.org/schema/tx”
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd

XML konfigurasyon dosyamizi inceleyecek olursak;
Oncelikle PropertyPlaceholderConfigurer sinifini kullaniyoruz. location property degeri icin ekledigimiz jdbc.properties dosyamizin path bilgisini veriyoruz.

Daha sonrasinda DataSource implemantation olarak DriverManagerDataSource sinifini kullaniyoruz. $ karakteri yardimi ile jdbc.properties dosyamizda yer alan bilgileri yaziyoruz.

SessionFactory olarak org.springframework.orm.hibernate5.LocalSessionFactoryBean sinifini kullaniyoruz.

@Transaction annotation ini aktif etmek icin <tx:annotation-driven> tagini kullaniyoruz.
Son olarak transaciton yonetimi icin org.springframework.orm.hibernate5.HibernateTransactionManager sinifini kullaniyoruz ve burada sessionFactory i inject ediyoruz.

27.hibernate.xml

<?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" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	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/tx
	http://www.springframework.org/schema/tx/spring-tx.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="_27" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>


	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>classpath:jdbc/jdbc.properties</value>
		</property>
	</bean>

	<bean id="dataSourceId"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>


	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

		<property name="dataSource" ref="dataSourceId" />
		<property name="packagesToScan" value="_27.hibernate.domain" />

		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">false</prop>
				<prop key="hibernate.hbm2ddl.auto">create</prop>
			</props>
		</property>

	</bean>

	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />


	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</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	
	-->
	/WEB-INF/27.hibernate.xml			   						  					
	</param-value> 			
    </init-param>	
	<load-on-startup>1</load-on-startup>
</servlet>

Web Layer & View Layer

Controller sinifimiz ve JSP dosyamiz onceki bolumde oldugu gibi olacak.
Ilgili aciklamalari inceleyebilirsiniz. Tabi ayri bir package ve folder altinda Controller sinifimizi ve JSP dosyamizi ekledik. (_27.hibernate.controller , 27.hibernate.view )

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.

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 to Sefa Cancel reply

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