Spring Tutorial – JPA (Java persistence API) with spring framework

Spring Data JPA

Spring Tutorial – JPA (Java persistence API) with spring framework

Overview

The Object Relational Mapping (ORM) concept is much-favoured these days because of the relative advantages it offers over relational database systems. ORM makes managing database a simpler task than do relational database systems. Enterprises want to spend as less time as possible on modifying SQL queries when database types are changed. Spring JPA, which is ORM-based, makes SQL queries database agnostic based on certain conditions. Given the capabilities of JPA, it is ahead of other data persistence solutions available in the market.








What is ORM?

Object Relationship Mapping (ORM) is a method for mapping database tables to classes. ORM represents a new way of querying database. The main difference between the ORM-way of database querying and SQL-like querying is that the latter is applicable only in the case of SQL but ORM query can work on any database. ORM makes software applications object oriented.

When the ORM method is applied, each database table is mapped to a class. Two frameworks are available for implementing the ORM method: Hibernate Framework and the Java Persistence API. To understand the main benefit of ORM, let us use an example. A project is using MySQL but a decision is made after some days to use Oracle instead. In this case, there is no need to change the query totally because the ORM query is global in nature. The changes in query will be minimal in nature.

Why JPA?

There are several options available to software developers for storing and retrieving persistent data in the database which include serialization, JDBC, JDO, proprietary object-relational mapping tools, object databases, and EJB 2 entity beans. However, except JDO, all options are limited. JPA overcomes these limitations and provides a comprehensive data persistence solution. It also significantly reduces the overhead tasks software developers need to perform when they manage database operations.  Provided below are a few compelling reasons JPA is a comprehensive data persistence solution.

All round capabilities

While almost all data persistence frameworks or tools are limited in their capabilities, JPA goes many steps beyond. To give a few examples of the limitations of the other tools, with Serialization, it is easy to store object graph information easily, it is unable to manage large volumes of data. JDBC API is a better option than Serialization but is difficult to use. ORM mapping frameworks are limited because they are bound by vendor-specific databases. JPA combines the strengths of the systems mentioned above but also overcomes their limitations.

No overhead tasks

Managing database operations is a high-investment proposition because it requires time and effort. JPA allows software developers focus on their core jobs and takes care of database management. Enterprises are able to devote more time towards core, high-priority jobs.

Database agnostic

Modifying SQL queries depending on different databases is a resource-consuming proposition. Though all databases accept SQL as standard, SQL dialects differ. JPA provides a database independent-agnostic on top of SQL. This removes the dependency of SQL on databases.

What is Spring JPA?

Spring JPA, also known as Spring Data JPA, is an API that facilitates implementing JPA-based repositories. It has been quite a problem to implement data access layers because of the tasks involved. There are too much of code to be implemented just to execute straightforward queries; perform data auditing and pagination. Spring JPA solves these pain points by letting the developer focus on their main tasks – writing repository interfaces which include custom finder methods – and taking care of the implementation. The salient features of Spring Data JPA are:

  • Support for XML-based entity mapping.
  • Transparent domain class auditing.
  • Support for pagination and dynamic query execution.
  • Support for integrating custom data access code.
  • JavaConfig based configuration of repository by introducing @EnableJpaRepositories.

What are the ORM components?

There has been a shift from relational database to object database because the latter offers comparative advantages over the former. Enterprises experience significant difficulties in data maintenance with relational database. Object databases perform storing, retrieving, updating, and maintenance of databases. At the core of object databases is the orm.xml file which, obviously, is XML-based. Since there is no need to compile XML, it is easy to edit multiple data sources with minimal administration. Object Relational Mapping (ORM) is a programming technique to convert relational data into object type and vice versa.  The main ORM components are described below:

  • Ability to write persistence classes with the help of object oriented classes.
  • Stable and reliable objects, entities and grids.
  • High performing architecture.

Environment setup:

Setting up the environment for Spring based application development involves just three major steps.

  • Setting up Java Development Kit

Download JDK from the Oracle site and then, install and configure it. Then the PATH and JAVA_HOME environment variables must be set.

  • Setting of Eclipse IDE

Eclipse can be downloaded from the official website. Once downloaded, unpack the binaries and then set the PATH as well.

  • Setting up Spring libraries along with JPA jar files

The Spring libraries may be obtained from http://repo.spring.io/release/org/springframework/spring/. Again, it is important to set the CLASSPATH correctly.








Now your environment is ready to start developing Spring JPA with Java applications.

Sample application:

In this section we will create a product object and populate it with data. We will be using Spring JPA for data persistence.

Listing 1: This is a POJO class containing product data

package techalpine.spring.jpa.com;

public class Product {

//This is the POJO class

private int id;

private String name;

private double price;

public Product(int id, String name, double price)

{

this.id=id;

this.name=name;

this.price=price;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

}

Following is the XML configuration file for mapping database table with the PODJ fields.

Listing 2: This is XML mapping with the table

<?xml version=“1.0” encoding=“UTF-8”?>

<entity-mappings version=“1.0”

xmlns=“http://java.sun.com/xml/ns/persistence/orm”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=“http://java.sun.com/xml/ns/persistence/orm  

        http://java.sun.com/xml/ns/persistence/orm_1_0.xsd “>

<entity class=techalpine.spring.jpa.com.Product”>

<table name=“product”></table>

<attributes>

<id name=“id”>

<column name=“id”/>

</id>

<basic name=“name”>

<column name=“name”/>

</basic>

<basic name=“price”>

<column name=“price”/>

</basic>

</attributes>

</entity>

</entity-mappings>

Following is the DAO class for the product object.

Listing 3: This is DAO class for the product

package techalpine.spring.jpa.com;

import java.util.List;

import org.springframework.orm.jpa.JpaTemplate;

import org.springframework.transaction.annotation.Transactional;

@Transactional

public class ProductDao {

JpaTemplate template;

public void setTemplate(JpaTemplate template) {

this.template = template;

}

public void createProduct(int id,String name,double price){

Product product = new Product(id,name,price);

template.persist(product);

}

public List<Product> getAllProducts(){

List<Product> products =template.find(“select pro from Product pro”);

return products;

}

}

This is the application context for mapping all the relevant beans.

Listing 4: This is application context

<?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:tx=“http://www.springframework.org/schema/tx”

xsi:schemaLocation=“http://www.springframework.org/schema/beans  

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  

    http://www.springframework.org/schema/tx 

    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>

<tx:annotation-driven transaction-manager=“jpaTxnManagerBean” proxy-target-class=“true”/>

<bean id=“dataSrcBean” class=“org.springframework.jdbc.datasource.DriverManagerDataSource”>

<property name=“driverClassName” value=“oracle.jdbc.driver.OracleDriver”></property>

<property name=“url” value=“jdbc:oracle:thin:@localhost:1524:xe”></property>

<property name=“username” value=“test”></property>

<property name=“password” value=“test123”></property>

</bean>

<bean id=“hbAdptrBean” class=“org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter”>

<property name=“showSql” value=“true”></property>

<property name=“generateDdl” value=“true”></property>

<property name=“databasePlatform” value=“org.hibernate.dialect.OracleDialect”></property>

</bean>

<bean id=“cmfBean” class=“org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”>

<property name=“dataSource” ref=“dataSrcBean”></property>

<property name=“jpaVendorAdapter” ref=“hbAdptrBean”></property>

</bean>

<bean id=“jpaTmpltBean” class=“org.springframework.orm.jpa.JpaTemplate”>

<property name=“entityManagerFactory” ref=“cmfBean”></property>

</bean>

<bean id=“productDaoBean” class= techalpine.spring.jpa.com.ProductDao”>

<property name=“template” ref=“jpaTmpltBean”></property>

</bean>

<bean id=“jpaTxnManagerBean” class=“org.springframework.orm.jpa.JpaTransactionManager”>

<property name=“entityManagerFactory” ref=“cmfBean”></property>

</bean>

</beans>

Now, this is the main class to check the population of the product object and retrieve it from the database.

Listing 5: This is the main class to check the output

package techalpine.spring.jpa.com;

import java.util.List;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class ProductTest {

public static void main(String[] args){

ApplicationContext context = new FileSystemXmlApplicationContext(

“META-INF/applicationContext.xml”);

ProductDao productDao = context.getBean(“productDaoBean”,ProductDao.class);

productDao.createProduct(123,”product1″,233.55);

productDao.createProduct(20,”product2″,350.70);

System.out.println(“Products created successfully”);

List<Product> products = productDao.getAllProducts();

System.out.println(“Products details are:”);

for (int i = 0; i < products.size(); i++) {

Product pro = products.get(i);

System.out.println(pro.getId() + ” : ” + pro.getName() + ” (” + pro.getPrice() + “)”);

}

}

}

One this class is executed, following output will be displayed.

Products created successfully

Products details are:

123:product1:233.55

20:product2:350.70








Conclusion

Since JPA and ORM are both based on XML, their dependence on other technologies or solutions are lesser than other persistence solutions. However, the idea of ORM and JPA will take some time to find some traction because enterprises will require time to move away from legacy database systems. Also, the jury is out on whether the JPA is a solution for all database problems as it is projected to be.

 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share