Spring – 23 – Hibernate

Merhaba Arkadaslar
Bu bolumde Hibernate & Spring entegrasyonundan bahsedecegim.

Hibernate , 2 tane ORM urunu icermektedir.

  • Native Hibernate API
  • JPA implementation

JPA (Java Persistence API ) sadece bir sartnamedir/specificationdir. Eger bir ORM cozumu JPA kullanilacaksa bu durumda mutlaka bir JPA implementation secilmelidir. Iste bu implementation’lardan biri Hibernate ORM dir.

Hibernate 2001 yilinda Gavin King tarafindan EJB 2.0 Entity Beanlere karsilik olarak gelistirilmeye baslanmistir. Suan JBoss firmasi tarafindan gelistirilmesi devam etmektedir.

Hibernate bir urundur , ORM aracidir. JPA ise bir sartnamedir, kurallar butunudur.

Hibernate hem Native Hibernate API olarak ORM cozumu sunarken hem de JPA implementation olarak bir ORM cozumu saglar. Diledigimizi kullanabiliriz.

EclipseLink de Hibernate gibi bir ORM aracidir. EclipseLink , JPA 2.X in reference implementation’idir.

Onceki bolumlerde JPA implementation olarak EclipseLink kullandik. Burada ise JPA implemantation yerine Native Hibernate ‘in Spring entegrasyonu inceleyecegiz.

Oncelikle Native Hibernate icin projemize Maven dependency tanimlarini ekleyelim.

pom.xml

<properties>
	<!--last update : 26.10.2016 -->
	<hibernate.version>5.2.3.Final</hibernate.version>
</properties>


....
<dependencies>

	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-core</artifactId>
		<version>${hibernate.version}</version>
	</dependency>
</dependencies>

Person.java

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;

	public Person() {
		super();
	}

	public Person(String name, String surname, int salary) {
		super();
		this.name = name;
		this.surname = surname;
		this.salary = salary;
	}
        //getters and setters
...
}

PersonDAO.java

package _29.hibernate.dao;

import java.util.List;

import _29.hibernate.model.Person;

public interface PersonDAO {

	public void insert(Person person);

	public Person getPersonById(int id);

	public List<Person> getAllPersons();

	public void update(Person person);

	public void delete(int id);

}

PersonDAOImpl.java

Native Hibernate ve JPA da kullandigimiz arabirimleri eslestirecek olursak ;

  • Native Hibernate -> org.hibernate.SessionFactory
    JPA ->javax.persistence.EntityManagerFactory
  • Native Hibernate -> org.hibernate.Session
    JPA -> javax.persistence.EntityManager
  • Native Hibernate -> org.hibernate.Query
    JPA ->javax.persistence.Query
  • Native Hibernate -> org.hibernate.Transaction
    JPA -> javax.persistence.EntityTransaction

Yine metotlari inceleyecek olursak ufak tefek isim farkliliklari oldugunu gorebiliriz.

package _29.hibernate.dao;

import java.util.List;

import javax.persistence.TypedQuery;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.CommonQueryContract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import _29.hibernate.model.Person;

@Repository("personDAOImpl")
public class PersonDAOImpl implements PersonDAO {

	private SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession() {
		return sessionFactory.openSession();
	}

	@Override
	public void insert(Person person) {
		Session session = getSession();
		Transaction transacion = session.beginTransaction();
		session.persist(person);
		transacion.commit();
		session.close();
	}

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

	}

	@Override
	public List<Person> getAllPersons() {
		Session session = getSession();
		TypedQuery<Person> query = session.createQuery("Select e from Person e",Person.class);
		
		//org.hibernate.Query is deprecated
		//Query query = session.createQuery("Select e from Person e");
		//return query.list()
		return query.getResultList();
		/*
		 * @Deprecated
			@SuppressWarnings("UnusedDeclaration")
			public interface Query<R> extends TypedQuery<R>, CommonQueryContract {
			..
			}
		 */

	}

	@Override
	public void update(Person person) {
		Session session = getSession();
		Transaction transacion = session.beginTransaction();
		session.update(person);
		transacion.commit();
		session.close();
	}

	@Override
	public void delete(int id) {
		Person person = getPersonById(id);
		if (person != null) {
			Session session = getSession();
			Transaction transacion = session.beginTransaction();
			session.delete(person);
			transacion.commit();
			session.close();
		}

	}

}

29.hibernate.xml
Konfigurasyon dosyamizi inceledigimizde onceki ornegimizden farkli olarak EntityManagerFactory yerine SessionFactory icin bean tanimi yapiyoruz. Bunun icin LocalSessionFactoryBean sinifi tipinde bean olusturduk.
dataSource ve packagesToScan property’leri onceki ornekte acikladigim sekilde calismaktadir.

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

	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>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="sessionFactoryId"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

		<property name="dataSource" ref="dataSourceId" />
		<property name="packagesToScan" value="_29.hibernate.model" />
		
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">false</prop>
				<prop key="hibernate.hbm2ddl.auto">create-drop</prop> 
			</props>
		</property>
		
	</bean>

	<!-- @Autowired annotation kullaniyoruz. -->
	<context:component-scan
		base-package="_29.hibernate.dao" />

</beans>

HibernateTest.java sinifimizi calistirdigimizda ;

Found ... Person [id=1, name=oldName, surname=oldSurname, salary=1989]
After Update...
Found ... Person [id=1, name=Levent, surname=Erguder, salary=1989]
Oct 26, 2016 11:20:07 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Listing...
Person [id=2, name=James, surname=Gosling, salary=1955]
Person [id=3, name=Joshua, surname=Bloch, salary=1961]

Github kaynak dosyalar/ source folder
leventerguder/injavawetrust-spring-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 *