DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach
  • What Java DAO Layer Is Best for Your Project

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  1. DZone
  2. Data Engineering
  3. Databases
  4. Spring Data JPA - Part 1

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.

By 
Vinu Sagar user avatar
Vinu Sagar
·
Apr. 09, 20 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
13.9K Views

Join the DZone community and get the full member experience.

Join For Free

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:


Spring Data Relational database Database Data (computing) Spring Framework Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach
  • What Java DAO Layer Is Best for Your Project

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!