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

  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data JPA - Part 1

Trending

  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • How to Practice TDD With Kotlin
  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  1. DZone
  2. Data Engineering
  3. Databases
  4. Spring Data JPA With an Embedded Database and Spring Boot

Spring Data JPA With an Embedded Database and Spring Boot

You can use Spring Data JPA to persist data to an embedded H2 database with RESTful web services and some helpful Spring annotations.

By 
Gaurav Rai Mazra user avatar
Gaurav Rai Mazra
·
Updated Mar. 23, 17 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
96.0K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will create a RESTful web service that will use JPA to persist the data in an embedded database (H2). Also, you can read more on RESTful web services here.

Adding pom.xml Dependencies

We will add spring-boot-starter-jpa to manage dependencies. We will use the H2 embedded database server for persistence.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>


Creating Entities

We have three entities in the example project: Product, Rating, and User.

@Entity
@Table(name = "product_ratings", schema = "product")
public class Rating {
    @Id
    @GeneratedValue
    @Column(name="rating_id")
    private Long ratingId;

    private double rating;

    @Column(name="product_id")
    private String productId;

    @Column(name="user_id")
    private String userId;

    public Rating() {

    }

    public Rating(Long ratingId, double rating, String productId, String userId) {
        super();
        this.ratingId = ratingId;
        this.rating = rating;
        this.productId = productId;
        this.userId = userId;
    }
    //getters, setters, toString, hashCode, equals
}


@Entity annotation specifies that this is an entity class. @Table annotation specifies the primary table for an entity class. You can configure the table_name and schema using this annotation for the entity class. @Id specifies that this field is the primary key of the entity. @GeneratedValue specifies how the primary key will be generated. @Column is used to specify the mapped column for the property or field. You can also configure whether the property is unique, nullable, its length, precision, scale, and/or if you want to insert or update it in the table.

Creating Repositories

You can extend the JpaRepository, CrudRepository interface to create your repository.

@Transactional
public interface ProductRepository extends JpaRepository<Product, String> {

}


Here, I created a ProductRepository interface that extends the JpaRepository interface. You may wonder why, instead of writing a repository class, we created an interface and where it will be implemented? The simple answer is the SimpleJpaRepository class. A proxy is generated by Spring, and all the requests are catered by the SimpleJpaRepository.

This contains all the basic methods like find, delete, save, findAll, and a few sort-related/criteria-based search methods. There could be a case where you need to write your own specific method and, in my case, finding all the ratings of a product. This could be done as follows.

@Transactional
public interface RatingRepository extends JpaRepository<Rating, Long> {
    public Iterable<Rating> getRatingsByProductId(final String productId);
}


@EnableJpaRepositories

This annotation will enable JPA repositories. This will scan for Spring Data repositories in the annotated configuration class by default. You can also change the basePackages to scan in this annotation:

@SpringBootApplication
@EnableJpaRepositories
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}


In our example, we have used this annotation in our App class, so it will scan all the packages in and under com.gauravbytes.gkart

These are the few steps to create a simple JPA project. You can get the full code on GitHub.

A Few Important Points

If you are using the embedded server in the above example, then you may need to set the following configurations:

  • Adding schema.sql in the classpath, if you are using schema in your tables (entity classes). You can get a sample here.
  • You can change the datasource name (by default, testdb) and other properties. See org.springframework.boot.autoconfigure.jdbc.DataSourceProperties for a full list of properties that you can configure.
Database Spring Framework Spring Data Spring Boot Data (computing) Relational database

Published at DZone with permission of Gaurav Rai Mazra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data JPA - Part 1

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!