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

Spring Data JPA

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

Trosolwg

Y Mapio Perthynas Gwrthrych,,en,Mae mentrau eisiau treulio cymaint llai o amser â phosibl ar addasu ymholiadau SQL pan,,en,mae mathau'n cael eu newid,,en,sy'n seiliedig ar ORM,,en,yn gwneud cronfa ddata ymholiadau SQL yn agnostig yn seiliedig ar rai amodau,,en,O ystyried galluoedd JPA,,en,mae o flaen atebion dyfalbarhad data eraill sydd ar gael yn y farchnad,,en,Beth yw ORM,,en,Mapio Perthynas Gwrthrych,,en,yn ddull ar gyfer mapio tablau cronfa ddata i ddosbarthiadau,,en,Mae ORM yn cynrychioli ffordd newydd o holi cronfa ddata,,en,Y prif wahaniaeth rhwng y ffordd ORM o ymholi cronfa ddata a chwestiynu tebyg i SQL yw bod yr olaf yn berthnasol yn achos SQL yn unig ond gall ymholiad ORM weithio ar unrhyw gronfa ddata,,en,Mae ORM yn gwneud cymwysiadau meddalwedd yn wrthrych-ganolog,,en,Pan gymhwysir y dull ORM,,en,mae pob tabl cronfa ddata wedi'i fapio i ddosbarth,,en (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. gwanwyn 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. Mae dau fframwaith ar gael ar gyfer gweithredu'r dull ORM,,en,Fframwaith gaeafgysgu ac API Dyfalbarhad Java,,en,Deall prif fudd ORM,,en,gadewch inni ddefnyddio enghraifft,,en,Mae prosiect yn defnyddio MySQL ond gwneir penderfyniad ar ôl rhai dyddiau i ddefnyddio Oracle yn lle,,en,nid oes angen newid yr ymholiad yn llwyr oherwydd bod yr ymholiad ORM yn fyd-eang ei natur,,en,Bydd y newidiadau ymholiad yn fach iawn eu natur,,en,Pam JPA,,en,Mae sawl opsiwn ar gael i ddatblygwyr meddalwedd ar gyfer storio ac adfer data parhaus yn y gronfa ddata sy'n cynnwys cyfresoli,,en,offer mapio gwrthrych-berthynol perchnogol,,en,cronfeydd data gwrthrychau,,en,ffa endid,,en,ac eithrio JDO,,en,mae'r holl opsiynau'n gyfyngedig,,en,Mae JPA yn goresgyn y cyfyngiadau hyn ac yn darparu datrysiad dyfalbarhad data cynhwysfawr,,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, a EJB 2 entity beans. However, except JDO, all options are limited. JPA overcomes these limitations and provides a comprehensive data persistence solution. Mae hefyd yn lleihau'n sylweddol y tasgau uwchben y mae'n rhaid i ddatblygwyr meddalwedd eu cyflawni wrth reoli gweithrediadau cronfa ddata,,en,Isod ceir ychydig o resymau cymhellol Mae JPA yn ddatrysiad dyfalbarhad data cynhwysfawr,,en,Pob gallu crwn,,en,Er bod bron pob fframwaith neu offeryn dyfalbarhad data yn gyfyngedig yn eu galluoedd,,en,Mae JPA yn mynd lawer o gamau y tu hwnt,,en,I roi ychydig o enghreifftiau o gyfyngiadau'r offer eraill,,en,gyda Serialization,,en,mae'n hawdd storio gwybodaeth graff gwrthrych yn hawdd,,en,nid yw'n gallu rheoli llawer iawn o ddata,,en,Mae JDBC API yn opsiwn gwell na Serialization ond mae'n anodd ei ddefnyddio,,en,Mae fframweithiau mapio ORM yn gyfyngedig oherwydd eu bod wedi'u rhwymo gan gronfeydd data gwerthwr-benodol,,en,Mae JPA yn cyfuno cryfderau'r systemau a grybwyllir uchod ond mae hefyd yn goresgyn eu cyfyngiadau,,en,Dim tasgau uwchben,,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

Mae rheoli gweithrediadau cronfa ddata yn gynnig buddsoddiad uchel oherwydd mae angen amser ac ymdrech arno,,en,Mae JPA yn caniatáu i ddatblygwyr meddalwedd ganolbwyntio ar eu swyddi craidd ac yn gofalu am reoli cronfeydd data,,en,Gall mentrau neilltuo mwy o amser tuag at graidd,,en,swyddi â blaenoriaeth uchel,,en,Agnostig cronfa ddata,,en,Addasu,,en,mae ymholiadau yn dibynnu ar wahanol gronfeydd data yn gynnig sy'n cymryd llawer o adnoddau,,en,Er bod pob cronfa ddata yn derbyn SQL fel safon,,en,Mae tafodieithoedd SQL yn wahanol,,en,Mae JPA yn darparu cronfa ddata annibynnol-agnostig ar ben SQL,,en,Mae hyn yn dileu dibyniaeth SQL ar gronfeydd data,,en,Beth yw JPA y Gwanwyn,,en,a elwir hefyd yn Spring Data JPA,,en,yn API sy'n hwyluso gweithredu ystorfeydd sy'n seiliedig ar JPA,,en,Mae wedi bod yn dipyn o broblem gweithredu haenau mynediad at ddata oherwydd y tasgau dan sylw,,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?

gwanwyn 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. Mae gormod o god i'w weithredu dim ond i weithredu ymholiadau syml,,en,perfformio archwilio data a thudalennu,,en,Mae JPA y Gwanwyn yn datrys y pwyntiau poen hyn trwy adael i'r datblygwr ganolbwyntio ar eu prif dasgau - ysgrifennu rhyngwynebau ystorfa sy'n cynnwys dulliau darganfod arfer - a gofalu am y gweithredu,,en,Nodweddion amlwg,,en,yn,,en,Cefnogaeth ar gyfer mapio endidau yn seiliedig ar XML,,en,Archwilio dosbarth parth tryloyw,,en,Cefnogaeth ar gyfer pasiant a gweithredu ymholiadau deinamig,,en,Cefnogaeth ar gyfer integreiddio cod mynediad data wedi'i deilwra,,en,Cyfluniad ystorfa wedi'i seilio ar JavaConfig trwy gyflwyno @EnableJpaRepositories,,en,Beth yw'r cydrannau ORM,,en,Bu symudiad o gronfa ddata berthynol i gronfa ddata gwrthrychau oherwydd bod yr olaf yn cynnig manteision cymharol dros y cyntaf,,en; 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. Mae mentrau'n profi anawsterau sylweddol wrth gynnal data gyda chronfa ddata berthynol,,en,Mae cronfeydd data gwrthrychau yn perfformio storio,,en,adalw,,en,diweddaru,,en,a chynnal cronfeydd data,,en,Wrth wraidd cronfeydd data gwrthrychau mae'r ffeil orm.xml sydd,,en,yn seiliedig ar XML,,en,Gan nad oes angen llunio,,en,mae'n hawdd golygu sawl ffynhonnell ddata heb lawer o weinyddiaeth,,en,Mapio Perthynas Gwrthrych,,en,yn dechneg raglennu i drosi data perthynol yn fath o wrthrych ac i'r gwrthwyneb,,en,Disgrifir prif gydrannau ORM isod,,en,Y gallu i ysgrifennu dosbarthiadau dyfalbarhad gyda chymorth dosbarthiadau sy'n canolbwyntio ar wrthrychau,,en,Gwrthrychau sefydlog a dibynadwy,,en,endidau a gridiau,,en,Pensaernïaeth sy'n perfformio'n dda,,en,Sefydlu llyfrgelloedd y Gwanwyn ynghyd â ffeiliau jar JPA,,en,Nawr mae eich amgylchedd yn barod i ddechrau datblygu Spring JPA gyda chymwysiadau Java,,en. 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:

Yn yr adran hon byddwn yn creu gwrthrych cynnyrch ac yn ei boblogi â data,,en,Byddwn yn defnyddio Spring JPA ar gyfer dyfalbarhad data,,en,Dosbarth POJO yw hwn sy'n cynnwys data cynnyrch,,en,techalpine.spring.jpa.com,,en,Dyma'r dosbarth POJO,,en,id = id,,en,enw = enw,,en,pris = pris,,en,getId,,en,setId,,id,id = id,,en,getPrice,,en,Canlynol yw'r ffeil ffurfweddu XML ar gyfer mapio tabl cronfa ddata gyda'r meysydd PODJ,,en,Dyma fapio XML gyda'r tabl,,en,fersiwn mapio endid =,,en,java.sun.com/xml/ns/persistence/orm,,en,java.sun.com/xml/ns/persistence/orm_1_0.xsd,,en,dosbarth endid =,,en,gwanwyn.jpa.com.Product,,en,enw'r tabl =,,en,bwrdd,,en,enw id =,,en,enw colofn =,,en,enw sylfaenol =,,en,syml,,en,endid,,en,mapio endidau,,en,Canlynol yw'r dosbarth DAO ar gyfer gwrthrych y cynnyrch,,en,Dyma ddosbarth DAO ar gyfer y cynnyrch,,en,pecyn techalpine.spring.jpa.com,,en,mewnforio org.springframework.orm.jpa.JpaTemplate,,en,mewnforio org.springframework.transaction.annotation.Transactional,,en,@Transactional,,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;

cyhoeddus dosbarth Product {

//This is the POJO class

preifat int id;

preifat String name;

preifat double price;

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

{

hwn.id=id;

hwn.name=name;

hwn.price=price;

}

cyhoeddus int getId() {

return id;

}

cyhoeddus unedau gwag setId(int id) {

hwn.id = id;

}

cyhoeddus String getName() {

return enw;

}

cyhoeddus unedau gwag setName(String name) {

hwn.name = name;

}

cyhoeddus double getPrice() {

return price;

}

cyhoeddus unedau gwag setPrice(double price) {

hwn.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=“enw”>

<column name=“enw”/>

</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

dosbarth cyhoeddus ProductDao,,en,Templed JpaTemplate,,en,set gwagle cyhoeddusTemplate,,co,this.template = templed,,en,gwagle cyhoeddus createProduct,,en,int id,,en,pris dwbl,,en,Cynnyrch cynnyrch = Cynnyrch newydd,,en,template.persist,,en,getAllProducts,,nl,cynhyrchion = template.find,,en,dewiswch pro o Product pro,,en,dychwelyd cynhyrchion,,en,Dyma gyd-destun y cais ar gyfer mapio'r holl ffa perthnasol,,en,Dyma gyd-destun y cais,,en,tx =,,en,www.springframework.org/schema/tx,,en,www.springframework.org/schema/tx/spring-tx-3.0.xsd,,en,tx,,en,rheolwr trafodion sy'n cael ei yrru gan anodi;,,en,jpaTxnManagerBean,,eu,dosbarth dirprwy-targed =,,en,dataSrcBean,,gd,org.springframework.jdbc.datasource.DriverManagerDataSource,,en,oracle.jdbc.driver.OracleDriver,,en,oracl,,en,tenau,,en,@localhost,,en,car,,vi,prawf123,,en,hbAdptrBean,,en,org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter,,en,sioeSql,,en,geneDdl,,en,cronfa ddataPlatform,,en,org.hibernate.dialect.OracleDialect,,en,cmfBean,,en,org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,,en,jpaVendorAdapter,,en,jpaTmpltBean,,en,org.springframework.orm.jpa.JpaTemplate,,ms {

JpaTemplate template;

public void setTemplate(JpaTemplate template) {

this.template = template;

}

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

Product product = new Product(id,enw,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”?>

<ffa 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=“yn wir”/>

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

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

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

<property name=“username” value=“prawf”></eiddo>

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

</ffa>

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

<property name=“showSql” value=“yn wir”></eiddo>

<property name=“generateDdl” value=“yn wir”></eiddo>

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

</ffa>

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

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

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

</ffa>

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

<property name=“endidManagerFactory,,en,cynnyrchDaoBean,,en,gwanwyn.jpa.com.ProductDao,,pt,org.springframework.orm.jpa.JpaTransactionManager,,ms,dyma'r prif ddosbarth i wirio poblogaeth gwrthrych y cynnyrch a'i adfer o'r gronfa ddata,,en,Dyma'r prif ddosbarth i wirio'r allbwn,,en,ProductTest,,en,META-INF / applicationContext.xml,,en,ProductDao productDao = context.getBean,,en,CynnyrchDao,,es,cynnyrchDao.createProduct,,en,cynnyrch1,,en,cynnyrch2,,en,Cynhyrchion wedi'u creu yn llwyddiannus,,en,cynhyrchion = productDao.getAllProducts,,en,Mae manylion cynhyrchion yn,,en,cynhyrchion.size,,en,Cynnyrch pro = products.get,,en,pro.getId,,en,pro.getName,,en,pro.getPrice,,en,Mae un y dosbarth hwn yn cael ei ddienyddio,,en,bydd yr allbwn canlynol yn cael ei arddangos,,en,Gan fod JPA ac ORM ill dau yn seiliedig ar XML,,en,mae eu dibyniaeth ar dechnolegau neu atebion eraill yn llai nag atebion dyfalbarhad eraill,,en” ref=“cmfBean”></eiddo>

</ffa>

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

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

</ffa>

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

<property name=“endidManagerFactory,,en,cynnyrchDaoBean,,en,gwanwyn.jpa.com.ProductDao,,pt,org.springframework.orm.jpa.JpaTransactionManager,,ms,dyma'r prif ddosbarth i wirio poblogaeth gwrthrych y cynnyrch a'i adfer o'r gronfa ddata,,en,Dyma'r prif ddosbarth i wirio'r allbwn,,en,ProductTest,,en,META-INF / applicationContext.xml,,en,ProductDao productDao = context.getBean,,en,CynnyrchDao,,es,cynnyrchDao.createProduct,,en,cynnyrch1,,en,cynnyrch2,,en,Cynhyrchion wedi'u creu yn llwyddiannus,,en,cynhyrchion = productDao.getAllProducts,,en,Mae manylion cynhyrchion yn,,en,cynhyrchion.size,,en,Cynnyrch pro = products.get,,en,pro.getId,,en,pro.getName,,en,pro.getPrice,,en,Mae un y dosbarth hwn yn cael ei ddienyddio,,en,bydd yr allbwn canlynol yn cael ei arddangos,,en,Gan fod JPA ac ORM ill dau yn seiliedig ar XML,,en,mae eu dibyniaeth ar dechnolegau neu atebion eraill yn llai nag atebion dyfalbarhad eraill,,en” ref=“cmfBean”></eiddo>

</ffa>

</ffa>

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;

mewnforio java.util.List;

mewnforio org.springframework.context.ApplicationContext;

mewnforio org.springframework.context.support.FileSystemXmlApplicationContext;

cyhoeddus dosbarth ProductTest {

cyhoeddus sefydlog unedau gwag prif(Llinyn[] args){

ApplicationContext context = newydd FileSystemXmlApplicationContext(

“META-INF/applicationContext.xml”);

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

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

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

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

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

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

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

Product pro = products.get(i);

System.allan.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








Casgliad

Since JPA and ORM are both based on XML, their dependence on other technologies or solutions are lesser than other persistence solutions. However, bydd y syniad o ORM a JPA yn cymryd peth amser i ddod o hyd i beth tyniant oherwydd bydd angen amser ar fentrau i symud i ffwrdd o systemau cronfa ddata etifeddol,,en,mae'r rheithgor yn gofyn a yw'r JPA yn ddatrysiad ar gyfer yr holl broblemau cronfa ddata fel y rhagwelir y bydd,,en. 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