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

Spring Data JPA

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

Orokorra

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. Bi marko daude eskuragarri ORM metodoa ezartzeko,,en,Hibernate Framework eta Java Persistence APIa,,en,ORMren onura nagusia ulertzeko,,en,erabil dezagun adibide bat,,en,Proiektu batek MySQL erabiltzen du baina egun batzuk igarota Oracle ordez erabiltzea erabakitzen da,,en,ez dago kontsulta guztiz aldatu beharrik, ORM kontsultak izaera globala duelako,,en,Kontsultaren aldaketek gutxieneko izaera izango dute,,en,Zergatik JPA,,en,Softwarearen garatzaileek hainbat aukera daude datu-basean datu iraunkorrak gordetzeko eta berreskuratzeko, serializazioa barne,,en,objektu-erlazio bidezko mapatze tresnak,,en,objektuen datu baseak,,en,entitate babarrunak,,en,JDO izan ezik,,en,aukera guztiak mugatuak dira,,en,JPAk muga horiek gainditzen ditu eta datuen iraupen konponbide integrala eskaintzen du,,en: 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, eta EJB 2 entity beans. However, except JDO, all options are limited. JPA overcomes these limitations and provides a comprehensive data persistence solution. Softwarearen garatzaileek datu-basearen eragiketak kudeatzen dituztenean burutzen dituzten gaineko zereginak ere nabarmen murrizten ditu,,en,Jarraian, JPA datuen iraupen konponbide integrala da,,en,Gaitasun borobil guztiak,,en,Datuen iraunkortasun esparru edo tresna ia guztiak beren gaitasunetan mugatuta dauden bitartean,,en,JPA haratago urrats asko egiten ditu,,en,Beste tresnen mugen adibide batzuk emateko,,en,Serializazioarekin,,en,erraza da objektuen grafikoen informazioa erraz gordetzea,,en,ezin da datu bolumen handiak kudeatu,,en,JDBC APIa Serializazioa baino aukera hobea da baina erabiltzeko zaila da,,en,ORM mapatze-esparruak mugatuak dira, saltzailearen berariazko datu-baseek lotzen dituztelako,,en,JPAk goian aipatutako sistemen indarguneak konbinatzen ditu, baina baita haien mugak gainditzen ere,,en,Zeregin orokorrik ez,,en. 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

Datu-basearen eragiketak kudeatzea inbertsio handiko proposamena da, denbora eta ahalegina eskatzen duelako,,en,JPA-k software garatzaileei beren oinarrizko lanetan oinarritzea ahalbidetzen die eta datu-baseak kudeatzeaz arduratzen da,,en,Enpresek denbora gehiago eskain dezakete muinari,,en,lehentasun handiko lanpostuak,,en,Datu-basearen agnostikoa,,en,Aldatzen,,en,Datu base desberdinen araberako kontsultak baliabideak kontsumitzen dituen proposamena da,,en,Datu base guztiek SQL estandar gisa onartzen badute ere,,en,SQL euskalkiak desberdinak dira,,en,JPA-k SQL-ren gaineko datu-base independente-agnostikoa eskaintzen du,,en,SQL datu-baseekiko mendekotasuna kentzen du,,en,Zer da Udaberriko JPA,,en,Spring Data JPA izenarekin ere ezaguna,,en,JPA oinarritutako biltegiak ezartzea errazten duen APIa da,,en,Datuetarako sarbiderako geruzak ezartzea nahiko arazo izan da inplikatutako zereginak direla eta,,en. 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 aplikazio:

Atal honetan produktuaren objektu bat sortuko dugu eta datuekin beteko dugu,,en,Udaberriko JPA erabiliko dugu datuen iraupenerako,,en,Produktuen datuak dituen POJO klasea da,,en,techalpine.spring.jpa.com,,en,Hau POJO klasea da,,en,id = id,,en,izena = izena,,en,prezioa = prezioa,,en,getId,,en,setId,,id,id = id,,en,lortuPrezioa,,en,Jarraian, datu basearen taula PODJ eremuekin mapatzeko XML konfigurazio fitxategia dago,,en,Hau taularekin XML mapeatzea da,,en,entitate-mapping bertsioa =,,en,java.sun.com/xml/ns/persistence/orm,,en,java.sun.com/xml/ns/persistence/orm_1_0.xsd,,en,entitate klasea =,,en,spring.jpa.com.Product,,en,taularen izena =,,en,mahaia,,en,ID izena =,,en,zutabearen izena =,,en,oinarrizko izena =,,en,oinarrizkoa,,en,entitatea,,en,entitate-mapak,,en,Jarraian, produktuaren objektuaren DAO klasea dago,,en,Hau DAO klasea da produktuarentzat,,en,pakete techalpine.spring.jpa.com,,en,inportatu org.springframework.orm.jpa.JpaTemplate,,en,inportatu org.springframework.transaction.annotation.Transactional,,en,@Transakzionala,,en. We will be using Spring JPA for data persistence.

Listing 1: This is a POJO class containing product data

package techalpine.spring.jpa.com;

publikoak klase Product {

//This is the POJO class

pribatua int id;

pribatua Kate izena;

pribatua bikoitza price;

publikoak Product(int id, Kate izena, bikoitza price)

{

hau.id=id;

hau.name=name;

hau.price=price;

}

publikoak int getId() {

return id;

}

publikoak gal setId(int id) {

hau.id = id;

}

publikoak String getName() {

return izena;

}

publikoak gal setName(Kate izena) {

hau.name = Izen;

}

publikoak bikoitza getPrice() {

return price;

}

publikoak gal setPrice(bikoitza price) {

hau.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=“izena”>

<column name=“izena”/>

</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,Kate izena,double price){

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

template.persist(product);

}

public List<Product> getAllProducts(){

zerrenda<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”?>

<babarrunak 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=“Egia”/>

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

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

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

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

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

</bean>

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

<property name=“showSql” value=“Egia”></jabetza>

<property name=“generateDdl” value=“Egia”></jabetza>

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

</bean>

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

<property name=“Datu-iturburua” ref=“dataSrcBean”></jabetza>

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

</bean>

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

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

</bean>

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

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

</bean>

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

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

</bean>

</babarrunak>

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;

inportatu java.util.List;

inportatu org.springframework.context.ApplicationContext;

inportatu org.springframework.context.support.FileSystemXmlApplicationContext;

publikoak klase ProductTest {

publikoak estatiko gal nagusia(Katea[] argumentuak){

ApplicationContext context = berriak FileSystemXmlApplicationContext(

“META-INF/applicationContext.xml”);

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

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

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

Sistema.errondan.println(“Products created successfully”);

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

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

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

Product pro = products.get(i);

Sistema.errondan.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








Ondorioa

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