34

Using the Spring Data JPA

 5 years ago
source link: https://www.tuicool.com/articles/hit/6J3iaii
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Spring Data JPAis not a JPA provider but a specification — it is a library/framework that adds an extra layer of abstraction on the top of our JPA provider. It simply “hides” the Java Persistence API and the JPA provider behind its repository abstraction.

JPA is the sun specification for persisting objects in the enterprise application. Therefore, it is used as a replacement for complex entity beans.

The implementation of JPA specifications is provided by many JPA providers, such as Hibernate, Toplink, iBatis, OpenJPA, etc.

Features Provided by Spring Data JPA:

  • Create and support repositories created with Spring and JPA
  • Support JPA queries
  • Support for batch loading, sorting, dynamical queries
  • Supports XML mapping for entities
  • Reduce code size for generic CRUD operations by using the CrudRepository

What Components Do We Need?

  • The JDBC driver  enables Java applications to interact with the database.
  • The data source provides all technical information needed to access data.
  • The JPA Provider implements the Java Persistence API. We use Hibernate because it is the most common JPA provider.
  • Spring Data JPA   hides the used JPA provider behind its repository abstraction.

The Java Persistence API is used for managing, persisting, and accessing data between objects and the relational database. Hibernate is an ORM (Object Relational Mapping) tool that implements JPA specification.

The following program illustrates how to integrate Spring with JPA, using the Hibernate as a JPA provider :

Exploring the Directory Structure

ZfuyQnB.png!web

  pom.xml file   : We will do this by adding Spring, Hibernate, and MySQL dependencies in the Maven project as shown below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.innovationM.hibernate</groupId>
  <artifactId>spring-hibernate-jpa-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring-hibernate-jpa-tutorial</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.9.Final</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
    </dependency>
    <dependency> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
      <version>6.0.5</version> 
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

JPA  Entity   class: This is entity class  Person consists of getter and setter methods.

package com.innovationM.spring.entity;

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

@Entity
@Table(name = "PERSONS")
public class Person {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @Column(name = "FIRST_NAME")
   private String firstName;

   @Column(name = "LAST_NAME")
   private String lastName;

   @Column(name = "EMAIL")
   private String email;

   public Person() {}

   public Person(String firstName, String lastName, String email) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.email = email;
   }

   //getter and setter methods.
}

Data Access Object (DAO) Class

PersonDao.java : This repository interface consists of methods implemented by the implementation class.

package com.innovationM.spring.dao;

import java.util.List;

import com.innovationM.spring.entity.Person;

public interface PersonDao {
   void add(Person person);
   List<Person> listPersons();
}

  PersonDaoImp.java : This repository class implements the   PersonDao interface to provide a method body accordingly as to persist data in the database.

package com.innovationM.spring.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.innovationM.spring.entity.Person;

@Repository
public class PersonDaoImp implements PersonDao {

   @PersistenceContext
   private EntityManager em;

   @Override
   public void add(Person person) {
      em.persist(person);
   }

   @Override
   public List<Person> listPersons() {
      CriteriaQuery<Person> criteriaQuery = em.getCriteriaBuilder().createQuery(Person.class);
      @SuppressWarnings("unused")
      Root<Person> root = criteriaQuery.from(Person.class);
      return em.createQuery(criteriaQuery).getResultList();
   }

}

Service Class

PersonService.java :   This interface consists of methods to be implemented by the implementation class at the service layer.

package com.innovationM.spring.service;

import java.util.List;

import com.innovationM.spring.entity.Person;

public interface PersonService {
    void add(Person person);
    List<Person> listPersons();
}

PersonServiceImp.java : This service class implements the   PersonService interface to provide a method body according to our business logic.

package com.innovationM.spring.service;

import java.util.List;

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

import com.innovationM.spring.dao.PersonDao;
import com.innovationM.spring.entity.Person;

@Service
public class PersonServiceImp implements PersonService {

   @Autowired
   private PersonDao userDao;

   @Transactional
   public void add(Person person) {
      userDao.add(person);
   }

   @Transactional(readOnly = true)
   public List<Person> listPersons() {
      return userDao.listPersons();
   }

}

  persistence.xml file   : This XML file contains information to connect with the database.

<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="LOCAL_PERSISTENCE">
    <description> Spring Hibernate JPA Configuration Example</description>
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</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/demo" />
      <property name="javax.persistence.jdbc.user" value="root" />
      <property name="javax.persistence.jdbc.password" value="root" />
      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>

  </persistence-unit>
</persistence>

Spring configuration : This is a configuration class with the @EnableTransactionManagement annotation to enable transaction management capability.

package com.innovationM.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.innovationM.spring.dao"),
      @ComponentScan("com.innovationM.spring.service") })
public class AppConfig {

   @Bean
   public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() {
      LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
      factoryBean.setPersistenceUnitName("LOCAL_PERSISTENCE");
      return factoryBean;
   }

   @Bean
   public JpaTransactionManager geJpaTransactionManager() {
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject());
      return transactionManager;
   }
}

Run application:This is the main class to run the application.

package com.innovationM.spring;

import java.sql.SQLException;
import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.innovationM.spring.config.AppConfig;
import com.innovationM.spring.entity.Person;
import com.innovationM.spring.service.PersonService;

public class MainApp {
   public static void main(String[] args) throws SQLException {
      AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(AppConfig.class);

      PersonService personService = context.getBean(PersonService.class);

      // Add Persons
      personService.add(new Person("Rahul", "Gupta", "[email protected]"));
      personService.add(new Person("Akshay", "Sharma", "[email protected]"));
      personService.add(new Person("Ankit", "Sarraf", "[email protected]"));

      // Get Persons
      List<Person> persons = personService.listPersons();
      for (Person person : persons) {
         System.out.println("Id = "+person.getId());
         System.out.println("First Name = "+person.getFirstName());
         System.out.println("Last Name = "+person.getLastName());
         System.out.println("Email = "+person.getEmail());
         System.out.println();
      }

      context.close();
   }
}

Output:We will get the following output on the console.

Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into PERSONS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: select person0_.id as id1_0_, person0_.EMAIL as EMAIL2_0_, person0_.FIRST_NAME as FIRST_NA3_0_, person0_.LAST_NAME as LAST_NAM4_0_ from PERSONS person0_
Id = 1
First Name = Rahul
Last Name = Gupta
Email = [email protected]

Id = 2
First Name = Akshay
Last Name = Sharma
Email = [email protected]

Id = 3
First Name = Ankit
Last Name = Sarraf
Email = [email protected]

You can download this example here .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK