Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Getting Started with Persistence in Spring Framework

This article presents the integration of two key technologies used in the Java world: the JPA specification and the Spring Framework. In addition we will create a CRUD Java to expose the step by step of the integration process.

The Java Database Connectivity (JDBC) is an API known that provides a set of resources that can be used in the inter-relationship between Java and a lot of SQL database applications. The persistence of Java data through the use of JDBC was always a laborious task for the developer because most use in databases on the market work in the relational paradigm, however, Java applications are developed in the paradigm of object-oriented, which causes during the process of relationship between these two paradigms considerable problem, which is given the name of Impedance mismatch.

However, with the use of JPA this problem becomes transparent by supplying the developer to an API that supports the object-relational mapping through the use of metadata in the application code.

The JPA specification is recognized as one of the most used data persistence strategies in the Java world, this because it provides a set of features that view facilitate the development of continuing activities. Its highlight the object/relational mapping, which provides the mapping database through annotations used in the actual application source code. The Spring is a framework that aims to simplify the development of Java projects through various features offered by such as dependency injection, transaction management, integration with various technologies, etc. Together, these two features will make your experience as a developer much easier by abstracting much of the complexity involved in the Java application development process. Following know them better and how to integrate them.

API JPA

The Java Persistence API (JPA) is a Java EE platform specification represented by the JSR-000338. It provides the developer a great ease in performing object-relational mappings and also in managing relational data in Java applications. The JPA is made up of four areas: (a) the Java Persistence API (b) query language (JPQL), (c) the Criteria API and (d) metadata for object relational mapping.

One of the great advantages of JPA is that this specification is not bound to only one implementation, ie, there are several implementations available on the market, which allows you to choose which you prefer, not letting him tied to a specific vendor. Two of the most used are provided by Hibernate and EclipseLink projects (Links section), both implemented within the specification provided by Oracle.

Another advantage is that we can highlight the fact that it can be used in conjunction with other technologies, including those that are not part of the Java EE platform, such as the Spring Framework. The union of these two technologies is widely used in the software development market because both have gained wide acceptance among the community, represented the joining of an API that facilitates the management of relational data in Java applications with a framework that recognized simplifies the development of these applications.

Spring Framework

This framework aims to simplify application development. It is maintained by Spring Source and its proposal is a lightweight solution for building enterprise applications. However, Spring is modular, allowing you to use only the components you need. You can use the IoC container with Struts in the view layer, but can only use the integration with Hibernate, for example. The Spring Framework supports management of declarative transactions, remote access to your logic using RMI or web services and various options for persisting data.

The Spring found a very strong user base over the years. Software companies saw in this framework a more appropriate structure for your needs.

Project

To demonstrate the integration of the technologies presented in this article, we will create a Java project which will be implemented the four operations of a CRUD from the JPA services in conjunction with the Spring Framework. The implementation of these methods will be using the IDE Eclipse Luna and will use the Maven (Links section) to manage the project configuration.

The first step is to create a new Maven project: for this we must access the File> New> Order> Maven Project. After clicking Next will appear the following dialog box in Figure 1. The option Create a simple Project (skip archetype selection) should be selected so that it creates an empty project.

Integrating JPA with Spring Framework

Figure 1. First Maven Project creation screen

The next step is to fill in the fields the way it is being shown in Figure 2 and the end press the Finish button to create the project.

Integrating JPA with Spring Framework

Figure 2. Second Maven Project creation screen

Project layers

The project will be developed in three layers: model, persistence business. This division aims to carry out a separation of function classes.

The model layer is responsible for the implementation of persistent entities, the layer persistence have classes that perform the database access activities (persists, update, delete and search), while the business layer will be formed by the business classes, or is responsible for conducting the business rule application. Because of this, to better organize the project will create four packages: com.mrbool.model, com.mrbool.persistence, com.mrbool.business and com.mrbool.run.

Project Setup

Before the implementation process begins it is necessary that the project is configured from two XML files: pom.xml and spring-context.xml.

The pom.xml file, shown in Listing 1, is used to make the settings that will be managed by Maven. We can enter the premises of the project, as well as plugins to be installed. In the example which will be developed in this article will be used etedependências:

  • spring-context: the Spring Framework module responsible for building a solid foundation in Spring applications and is based on Core and Beans modules. The main point of this module is the applicationContext.xml interface that inherits BeansFactory, but showing additional features to the latter. An example of this is the fact that the Context module also manage the bean life cycle of other suppliers, such as some specifications implementations of the Java EE platform and Hibernate provider;
  • spring-tx: the Spring Framework module responsible for the transaction programming for various API such as JTA, JDBC, Hibernate, JDO and JPA;
  • spring-orm: module responsible for working with object/relational mapping an application. It has integration with solutions such as Hibernate, JPA and JDO;
  • spring-aop: Spring module responsible for aspect-oriented programming;
  • hibernate-entitymanager: Implementation provided by Hibernate JPA specification;
  • commons-dbcp2: module provided to Apache foundation (Links section) and responsible for the creation and connection pools for databases;
  • mysql-connector-java: implementation of JDBC for MySQL DBMS.

In addition to the facilities they were also set up two plugins that will be used in the project: maven-compiler-plugin and maven-jar-plugin. The first is responsible, among other things, establish the JDK version to be used in the project, while the second manages the execution of the application, including defining the main class to run.

Listing 1. pom.xml file

<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.mrbool</groupId>
        <artifactId>spring-jpa</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring-jpa</name>
        <dependencies>
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                    <version>4.2.4.RELEASE</version>
              </dependency>
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-tx</artifactId>
                    <version>4.2.4.RELEASE</version>
              </dependency>
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-orm</artifactId>
                    <version>4.2.4.RELEASE</version>
              </dependency>
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                    <version>4.2.4.RELEASE</version>
              </dependency>
              <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                    <version>4.1.6.Final</version>
              </dependency>
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                    <version>4.2.4.RELEASE</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>5.1.38</version>
              </dependency>
        </dependencies>
        <build>
              <plugins>
                    <plugin>
                          <artifactId>maven-compiler-plugin</artifactId>
                          <version>3.3</version>
                          <configuration>
                                <source>1.8</source>
                                <target>1.8</target>
                          </configuration>
                    </plugin>
                    <plugin>
                          <groupId>org.apache.maven.plugins</groupId>
                          <artifactId>maven-jar-plugin</artifactId>
                          <configuration>
                                <archive>
                                     <manifest>
                                           <mainClass>com.mrbool.run.Run</mainClass>
                                     </manifest>
                                </archive>
                          </configuration>
                    </plugin>
   
              </plugins>
        </build>
  </project>

The second file to be configured is the spring-context.xml, shown in Listing 2. It must be created inside the package src/main/resources and establishes the Spring Framework context settings in this project were made by injecting beans and setting specific tags. Configured beans were:

  • mysqlDataSource: defines the connection to the MySQL DBMS;
  • EntityManagerFactory: sets the EntityManager, which will be responsible for managing the implementation of entities. In this bean are also passed information related to the persistence unit and the connection data with the DBMS;
  • transactionManager: defines the bean responsible for managing the transactions carried out by the EntityManager;

Listing 2. File spring-context.xml

<? 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: context=“http://www.springframework.org/schema/context"
        xmlns: tx=“http://www.springframework.org/schema/tx"
        xsi: schemaLocation=“
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd ">
   
        <Bean id=“EntityManagerFactory"
              class=“org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
              <Property name=“persistenceUnitName" value=“DevMedia-UP" />
              <Property name=“dataSource" ref=“mysqlDataSource" />
              <Property name=“jpaVendorAdapter">
        <Bean class=“org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
              </ Property>
        </ Bean>
        <Bean id=“mysqlDataSource" class=“org.apache.commons.dbcp2.BasicDataSource">
              <Property name="driverClassName" value="com.mysql.jdbc.Driver" />
              <Property name=“url"
                    value="jdbc:mysql://localhost/studentdb createDatabaseIfNotExist = true?" />
              <Property name=“username" value=“root" />
              <Property name=“password" value=“123456" />
        </ Bean>
        <Bean id=“transactionManager" class=“org.springframework.orm.jpa.JpaTransactionManager">
              <Property name=“EntityManagerFactory" ref=“EntityManagerFactory" />
        </ Bean>
        <Tx: annotation-driven />
   
        <! - Defines the base package for scanning the context of notes (@Component, @Repository, @Service, @Controller, etc.) ->
        <Context: component-scan base-package=“com.mrbool" />
        <Context: annotation-config />
   
  </ Beans>

Implementation of the project classes

The basic settings of the project have already been carried out and the next step is to start the implementation of the classes. The first to be developed will be StudentEntity, shown in Listing 3. This is actually an entity managed persistence JPA container and responsible for conducting the data between the application and the DBMS, as the JPA uses metadata, or is, notes to make the object/relational mapping. In the class are present the following JPA annotations:

  • Entity: Class notation used to define a new JPA entity;
  • Table: Class notation used to define the settings that the class will have when mapped to table a DBMS;
  • Id: attribute or annotation method responsible for defining the primary key of the table;
  • GeneratedValue: attribute or annotation method responsible for defining the strategy of primary key generation. In this case it states that the primary keys are created by the DBMS itself;
  • Column: attribute or annotation method responsible for defining the settings for a column, such as name, size, etc.

Listing 3. Class StudentEntity

package com.mrbool.model;
  import java.util.Calendar;
   
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.Id;
  import javax.persistence.Table;
   
  @Entity
  @Table(name=“student")
  public class StudentEntity {
   
        @Id
        @GeneratedValue
        private Long id;
   
        @Column(name=“name")
        private String name;
        @Column(name=“registration")
        private String registration;
        @Column(name=“birth_date")
        private Calendar birthDate;
        @Column(name=“gender")
        private String gender;
   
        public Long getId() {
              return id;
        }
   
        public void setId(Long id) {
              this.id = id;
        }
   
        public String getName() {
              return name;
        }
   
        public void setName(String name) {
              this.name = name;
        }
   
        public Calendar getBirthDate() {
              return birthDate;
        }
   
        public void setBirthDate(Calendar birthDate) {
              this.birthDate = birthDate;
        }
   
        public String getGender() {
              return gender;
        }
   
        public void setGender(String gender) {
              this.gender = gender;
        }
  }

After the creation of StudentEntity class you must create and configure persistence.xml file, which should contain the persistence unit of information that, in turn, is used for the implementation of JPA. It must be created within the META-INF folder, located dento package src/main/resources and its contents must be the same in Listing 4.

Listing 4. persistence.xml file

<?xml version="1.0" encoding="UTF-8"?>
  <persistence version="2.1"
        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">
        <persistence-unit name="MRBOOL-UP" transaction-type="RESOURCE_LOCAL">
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <class>com.mrbool.model.StudentEntity</class>
              
              <properties>
                    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
                    <property name="hibernate.show_sql" value="true" />
                    <property name="hibernate.format_sql" value="true" />
                    <property name="hibernate.hbm2ddl.auto" value="update" />
              </properties>
        </persistence-unit>
  </persistence>

The second class to be implemented is the StudentPersistence, shown in Listing 5. This class is responsible for performing the actions of access to the database. Notice that two notes are present: PersistenceContext and Repository. The first defines the attribute that will receive the injection of the EntityManager, set up in spring-context.xml file. The second defines the class is stereotyped as a repository class and can be injected into other classes managed by Spring container.

The methods of StudentPersistence class are those who make access to the database and use the EntityManager.

Listing 5. Class StudentPersistence

package com.mrbool.persistence;
  import javax.persistence.EntityManager;
  import javax.persistence.PersistenceContext;
   
  import org.springframework.stereotype.Repository;
   
  import com.mrbool.model.StudentEntity;
   
  @Repository
  public class StudentPersistence {
   
        @PersistenceContext
        private EntityManager entityManager;
   
        public void persist(StudentEntity entity) {
              this.entityManager.persist(entity);
        }
   
        public StudentEntity search(Long id) {
              return this.entityManager.find(StudentEntity.class, id);
        }
   
        public void remove(StudentEntity studentEntity) {
              this.entityManager.remove(studentEntity);
        }
        
        public void update(StudentEntity studentEntity){
              this.entityManager.merge(studentEntity);
        }
   
  }

The third class is the StudentBusiness, shown in Listing 6. It is responsible for defining the business rules related to student. It can be observed three notes: Transactional, Service and autowired. Transactional annotation defines all methods of this class to perform JPA transactions will be managed by the Spring Framework, with a view to setting held in spring-context.xml. The Service annotation is stereotyping class as service and defines that it can be injected into other classes managed by the Spring container. Since the autowired notation defines the noted attribute must be injected in view of the settings already carried out in the case of our example, the studentPersistence attribute is injected automatically because StudentPersistence class was noted with Repository, which permits its injection into other classes.

Listing 6. Class StudentBusiness

package com.mrbool.business;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  import org.springframework.transaction.annotation.Transactional;
   
  import com.mrbool.model.StudentEntity;
  import com.mrbool.persistence.StudentPersistence;
   
  @Transactional
  @Service
  public class StudentBusiness {
   
        @Autowired
        private StudentPersistence studentPersistence;
   
        public void persistStudent(StudentEntity entity) {
              this.studentPersistence.persist(entity);
        }
   
        public StudentEntity searchStudent(Long id) {
              return this.studentPersistence.search(id);
        }
   
        public void removeStudent(Long id) {
              StudentEntity aux = this.searchStudent(id);
              this.studentPersistence.remove(aux);
        }
   
        public void updateStudent(StudentEntity studentEntity) {
              this.studentPersistence.update(studentEntity);
        }
  }

The fourth and final annotated class is the Run, shown in Listing 7, which is responsible for initiating the execution of the project and where the Spring context is started by creating the ClassPathXmlApplicationContext class. This takes as a parameter the name of the configuration file context of Spring, spring-context.xml. Thus, when the getBean method in the context attribute is invoked, all the dependency related to this bean injections will be performed.

Run the class is an example of the persistence of a new student organization.

Listing 7. Class Run

package com.mrbool.run;
  import org.springframework.context.ApplicationContext;
  import org.springframework.context.support.ClassPathXmlApplicationContext;
   
  import com.mrbool.business.StudentBusiness;
  import com.mrbool.model.StudentEntity;
   
  public class Run {
   
        private static StudentBusiness studentBusiness;
        private static ApplicationContext context;
   
        public static void main(String[] args) {
              context = new ClassPathXmlApplicationContext("spring-context.xml");
              studentBusiness = context.getBean(StudentBusiness.class);
              studentBusiness.persistStudent(new StudentEntity());
        }
  }

Conclusion

Note that the integration of two technologies widely used in the Java world facilitates the creation of a project with various activities, but without this developer spend a lot of time and code.

The application of the knowledge acquired in this article in their day to day as Java Developer you will provide a deep abstraction of complexity present in the database connection tasks and working with relational data-oriented applications objects that because the JPA offers as well as resources for setting up connections with many DBMSs, the possibility of an object/relational mapping within its own source code.

You can still do all this together with the plethora of resources that the Spring Framework offers you, including delegating to it the role of managing the JPA transactions, as well as take advantage of dependency injection and integration with several Java specifications and technologies other suppliers.

Links

Hibernate: http://hibernate.org/orm

EclipseLink: http://www.eclipse.org/eclipselink/

CommonsDBCP: https://commons.apache.org/proper/commons-dbcp/

MySQL: https://www.mysql.com/

Apache Maven: https://maven.apache.org/

Eclipse Luna: https://eclipse.org/luna/

Introduction to the Java Persistence API (Release7): https://docs.oracle.com/javaee/7/tutorial/persistence-intro.htm#BNBPZ

Java Persistence 2.1 Final Release for Evaluation: http://download.oracle.com/otndocs/jcp/persistence-2_1-fr-eval-spec/index.html

Spring Framework Reference Documentation: http://docs.spring.io/spring/docs/4.2.4.RELEASE/spring-framework-reference/htmlsingle/



Fabrí­cio Galdino is a software expert and has worked with IT analysis and business development for more than five years. It has extensive experience with testing, back and front-end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login