{{announcement.body}}
{{announcement.title}}

Spring Data JPA - Part 1

DZone 's Guide to

Spring Data JPA - Part 1

Take a look at this tutorial that demonstrates how Java Object Relational Mapping works as a method of managing relational databases in Java.

· Java Zone ·
Free Resource

Object Relational Mapping (ORM)

A Java Object is mapped with a table in the database. The fields in the class corresponds to fields in the database.Java Object field

Java Object field


Java
 




x
11


 
1
@Entity
2
@Table(name = "t_user")
3
public class User  {
4
    @Id
5
    @GeneratedValue(strategy = GenerationType.IDENTITY)
6
    private Long id;
7
    private String firstName;
8
    private String lastName;
9
    private String mobile;
10
    private String email;
11
}


This shows a typical representation of how the fields in the class are mapped to fields in the table.

We annotate the Class with  @Entity. We can also specify the table name. The fields in the class will correspond to the fields in the database.

Major ORM frameworks include Hibernate, Ibatis, EclipseLink and there are many more.

JPA stands for Java Persistence API. It is the standard for mapping Java Objects to a relational database. All the frameworks adhere to this specification. Here, we will use Hibernate, which conforms to JPA specification. All annotations like  @Entity,  @Table,  @Id which we have used above forms part of the JPA framework. 

When we talk of Spring data JPA, it simplifies everything for  developers. The data access and CRUD operations are made very simple with Spring Data JPA. We can have Java Interfaces called repositories which extends the JPA Repository, which has many finder methods that comes with the implementation. Spring Data JPA comes with ease of implementation of paging, sorting, auditing and even supports native query operations.

Let us see a small demonstration of our first implementation.

I use the following:

  1.  JDK 1.8
  2. IDE - IntelliJ
  3. Database - PostgreSQL
  4. PostgreSQL Tool - PgAdmin.

We will use the same user table as above. I will name it as  t_user.  Let us see the folder structure.

  1. The entity package with user entity. 
  2. The repository package with UserRepository.

The User Entity

Java
 




xxxxxxxxxx
1
43


1
package com.notyfyd.entity;
2
import javax.persistence.*;
3
@Entity
4
@Table(name = "t_user")
5
public class User {
6
    @Id
7
    @GeneratedValue(strategy = GenerationType.IDENTITY)
8
    private Long id;
9
    private String firstName;
10
    private String lastName;
11
    private String mobile;
12
    private String email;
13
    public Long getId() {
14
        return id;
15
    }
16
    public void setId(Long id) {
17
        this.id = id;
18
    }
19
    public String getFirstName() {
20
        return firstName;
21
    }
22
    public void setFirstName(String firstName) {
23
        this.firstName = firstName;
24
    }
25
    public String getLastName() {
26
        return lastName;
27
    }
28
    public void setLastName(String lastName) {
29
        this.lastName = lastName;
30
    }
31
    public String getMobile() {
32
        return mobile;
33
    }
34
    public void setMobile(String mobile) {
35
        this.mobile = mobile;
36
    }
37
    public String getEmail() {
38
        return email;
39
    }
40
    public void setEmail(String email) {
41
        this.email = email;
42
    }
43
}


The @Entity annotation specifies the class is an entity and is mapped to the database table. Here we specify the table name with the @Table annotation. We are giving it the name "t_user."

Note: Have fun with the table name as User. You are going to get errors. Check it out.

 @Id annotation is used to mark it as the primary key and the generation type we are using it as Identity. All the values are autogenerated sequentially without using a separate sequence.

The UserRepository

Java
 




xxxxxxxxxx
1
10
9


 
1
package com.notyfyd.repository;
2
import com.notyfyd.entity.User;
3
import org.springframework.data.jpa.repository.JpaRepository;
4
import org.springframework.stereotype.Repository;
5
@Repository
6
public interface UserRepository extends JpaRepository<User, Long> {
7
 
          


The repository extends JpaRepository which gives us access to many finder methods and delete methods. It also has methods which return Optional<User> which is very handy since we don't have to check for null values. They have methods like isPresent which is very useful to check the existence of Object.

The application.properties File

server.port=2003
spring.datasource.driver-class-name= org.postgresql.Driver
spring.datasource.url= jdbc:postgresql://192.168.64.6:30432/jpa-test
spring.datasource.username = postgres
spring.datasource.password = root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
  • The server port is the port on which I am running the application.
  • You need not change the driver name unless if you are using another database.
  • show-sql will give you the SQL statements created by Hibernate printed to the console. It is good to see that for your understanding.
  • I am using   ddl-auto =  create since Hibernate is going to create the tables for me automatically. Make sure you have already created the database.

My dependencies in the POM file:

XML
 




xxxxxxxxxx
1
27


 
1
<dependencies>
2
        <dependency>
3
            <groupId>org.springframework.boot</groupId>
4
            <artifactId>spring-boot-starter-data-jpa</artifactId>
5
        </dependency>
6
        <dependency>
7
            <groupId>org.springframework.boot</groupId>
8
            <artifactId>spring-boot-starter-web</artifactId>
9
        </dependency>
10
 
          
11
        <dependency>
12
            <groupId>org.postgresql</groupId>
13
            <artifactId>postgresql</artifactId>
14
            <scope>runtime</scope>
15
        </dependency>
16
        <dependency>
17
            <groupId>org.springframework.boot</groupId>
18
            <artifactId>spring-boot-starter-test</artifactId>
19
            <scope>test</scope>
20
            <exclusions>
21
                <exclusion>
22
                    <groupId>org.junit.vintage</groupId>
23
                    <artifactId>junit-vintage-engine</artifactId>
24
                </exclusion>
25
            </exclusions>
26
        </dependency>
27
    </dependencies>



You can run the application and see the user table created by Hibernate.

You can find the source code at GitHub.

You can find the video tutorial here:


Topics:
database ,java ,orm ,relational database ,spring boot ,spring data jpa ,spring jpa ,user entity

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}