Java hibernate dao save

DAO с Spring и Hibernate

Эта статья покажет, какimplement the DAO with Spring and Hibernate. Для базовой конфигурации Hibernate ознакомьтесь с предыдущей статьейHibernate 5 with Spring.

2. Больше никаких шаблонов Spring

Запуск Spring 3.0 и Hibernate 3.0.1,the Spring HibernateTemplate is no longer necessary для управления сеансом Hibernate. Теперь можно использоватьcontextual sessions —sessions managed directly by Hibernate и активировать их на протяжении всей транзакции.

Как следствие, в настоящее время рекомендуется использовать Hibernate API напрямую вместоHibernateTemplate.. Это эффективно полностью отделит реализацию уровня DAO от Spring.

2.1. Преобразование исключений безHibernateTemplate

Преобразование исключений было одной из обязанностейHibernateTemplate — перевод низкоуровневых исключений Hibernate на более высокие, общие исключения Spring.

Без шаблона аннотацияthis mechanism is still enabled and activefor all the DAOs annotated with the @Repository. Под капотом здесь используется постпроцессор bean-компонентов Spring, который сообщит всем bean-компонентам@Repository всеPersistenceExceptionTranslator, найденные в контексте Spring.

Следует помнить, что при трансляции исключений используются прокси. Чтобы Spring мог создавать прокси вокруг классов DAO, они не должны быть объявлены какfinal.

2.2. Управление сеансом гибернации без шаблона

Когда появилась поддержка Hibernate для контекстных сессий,HibernateTemplate по существу устарели. Фактически, Javadoc класса теперь выделяет этот аспект (выделено жирным шрифтом из оригинала):

Читайте также:  How to make an html document

3. DAO

Мы начнем сthe base DAO – an abstract, parametrized DAO, который поддерживает общие универсальные операции и который мы можем расширить для каждой сущности:

public abstract class AbstractHibernateDAO< T extends Serializable > < private Class< T >clazz; @Autowired private SessionFactory sessionFactory; public void setClazz(Class < T >clazzToSet) < clazz = clazzToSet; >public T findOne(long id) < return (T) getCurrentSession().get( clazz, id ); >public List < T >findAll() < return getCurrentSession() .createQuery( "from " + clazz.getName() ).list(); >public void save(T entity) < getCurrentSession().persist( entity ); >public T update(T entity) < return (T) getCurrentSession().merge( entity ); >public void delete(T entity) < getCurrentSession().delete( entity ); >public void deleteById(long id) < final T entity = findOne( id); delete( entity ); >protected final Session getCurrentSession() < return sessionFactory.getCurrentSession(); >>

Здесь интересно несколько аспектов — как уже говорилось, абстрактный DAO не расширяет какой-либо шаблон Spring (например,HibernateTemplate). Вместо этого HibernateSessionFactory вводится непосредственно в DAO и будет играть роль основного API Hibernate через контекстныеSession, которые он предоставляет:

Также обратите внимание, что конструктор получаетClass объекта как параметр, который будет использоваться в общих операциях.

Теперь давайте посмотрим наan example implementation of this DAO для объектаFoo:

@Repository public class FooDAO extends AbstractHibernateDAO < Foo >implements IFooDAO < public FooDAO()< setClazz(Foo.class ); >>

4. Заключение

В этой статье рассказывается о настройке и реализации уровня сохраняемости с помощью Hibernate и Spring.

Обсуждались причины прекращения использования шаблонов для уровня DAO, а также возможные подводные камни при настройке Spring для управления транзакциями и сеансом Hibernate. Конечный результат — легкая, чистая реализация DAO, практически не зависящая от Spring во время компиляции.

Реализацию этого простого проекта можно найти вthe github project.

Источник

Generic DAO in Hibernate

This article shows an example of implementation of Generic DAO in Hibernate for common CRUD operations. Generic DAO is used for not to repeat CRUD operation methods for each Entity DAO class.

Features

The example application will have following features. The complete source code is available at the end of this article.

  • A standalone Java application for performing database operations.
  • All database operations are performed using Hibernate
  • Transaction Manager configuration
  • A Generic DAO class for common DAO/CRUD operations
  • Specific DAO operations should be in respective Entity DAO class

Technology Stack

  • Spring Framework – 4.2.5.RELEASE
  • Hibernate – 4.3.11.Final
  • Database – PostgreSQL – 9.4
  • JDK – 7

Dependencies and project structure

Generic DAO Hibernate project structure

Generic DAO Hibernate project structure

Database

We are using PostgreSQL database for this example. We have an Employee table which holds basic employee details like firstname, lastname, designation, and salary. We will add some employees after creating table as test data for our application. The script for table creation and test data insert is as follows:

Spring and Hibernate Configuration

We are using XML free configuration so every configuration will be in Java files. The basic spring context configuration to load spring context and add ‘component scan’ will be in AppConfiguration.java We will keep all hibernate related configurations in a separate file called HibernateConfig.java . This file configures beans for DataSource, SessionFactory and Transaction Manager( HibernateTransactionManager ). The database URL and other configurable things are mentioned in application.properties file in classpath and loaded using @PropertySource annotation.

Generic DAO Interface and Implementation

Now we are creating an interface for generic dao called GenericDao.java . This interface will include all common DAO and CRUD operation methods required for each entity dao class. We should be having methods like Save, SaveOrUpdate, Delete, Find, Delete and Find All, findByExample, clear, flush, etc. You may add any additional methods if required.

Once the interface is defined we will be adding an abstract class AbstractGenericDao.java . This class will implement all the methods defined in GenericDao.java . We are keeping this as abstract as this shouldn’t be used directly by any service methods. All Entity Dao classes should extend it to use implementation provided by this class. As we are using Hibernate we need to inject the SessionFactory in AbstractGenericDao.java to implement all DAO methods. See the interface and implementation shown below:

Model, Service and DAO Layer

Now let’s add some services which will call some DAO methods. We will be using generic methods as well as a custom method written specifically for particular DAO. For our example, we have service methods to get all employees, save new employee if not exists and a custom method to get maximum salary given to any employee. To get all employees and save a new employee we will use methods defined in generic dao, which are findAll(), findAllByExample() and save(). To get the maximum salary we will be writing a custom method in EmployeeDao.java which is a DAO class belongs to Employee table.

EmployeeDao.java interface should extend to GenericDao.java interface to get all common methods. EmployeeDaoImpl.java should extend to AbstractGenericDao.java to access implementation of all generic methods. Thing to note here is if you have any other table then, that table’s DAO class can also get all generic methods by extending its interface and implementation class to GenericDao.java and AbstractGenericDao.java , which is the main purpose of having GenericDao.

Application class

Here is the application class MyApplication.java which will call services from the service layer. It will first get all employees, add a new one if it does not exist and then get all employees again. All these operations will use generic dao methods. After this, it will search for maximum salary given to any employee by calling a DAO method written specifically for Employee DAO.

Client Application

Finally, let’s check the client application. TestApplication.java which will load the spring context and call a method in MyApplication.java .

To test and run the application just run the TestApplication.java as Java application.

Source Code

The complete source code (maven project) is available at GitHub (keep java compilation level to 1.7).

Источник

Оцените статью