spring boot jpa examples

spring boot jpa examples

Spring Boot provides spring-boot-starter-data-jpa starter to connect Spring application with relational database efficiently. You can use it into project POM (Project Object Model) file.

Here, we are creating a spring-boot application which uses JPA to connect to the database.

Spring Boot provides default server and apache derby database. So, we will use that in our application.

Now, let's create project. Follow the following steps.

// pom.xml

<?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
<projectxmlnsprojectxmlns="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.javatpoint</groupId>  
    <artifactId>spring-boot-crud</artifactId>  
    <version>0.0.1-SNAPSHOT</version>  
    <packaging>jar</packaging>  
    <name>spring-boot-crud</name>  
    <description>spring boot application for crud</description>  
    <parent>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>2.0.0.BUILD-SNAPSHOT</version>  
        <relativePath/><!-- lookup parent from repository -->  
    </parent>  
    <properties>  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
        <java.version>1.8</java.version>  
    </properties>  
  
    <dependencies>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-data-jpa</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.derby</groupId>  
            <artifactId>derby</artifactId>  
            <scope>runtime</scope>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-test</artifactId>  
            <scope>test</scope>  
        </dependency>  
            <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-thymeleaf</artifactId>  
    </dependency>  
    </dependencies>  
    <build>  
        <plugins>  
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>  
        </plugins>  
    </build>  
    <repositories>  
        <repository>  
            <id>spring-snapshots</id>  
            <name>Spring Snapshots</name>  
            <url>https://repo.spring.io/snapshot</url>  
            <snapshots>  
                <enabled>true</enabled>  
            </snapshots>  
        </repository>  
        <repository>  
            <id>spring-milestones</id>  
            <name>Spring Milestones</name>  
            <url>https://repo.spring.io/milestone</url>  
            <snapshots>  
                <enabled>false</enabled>  
            </snapshots>  
        </repository>  
    </repositories>  
    <pluginRepositories>  
        <pluginRepository>  
            <id>spring-snapshots</id>  
            <name>Spring Snapshots</name>  
            <url>https://repo.spring.io/snapshot</url>  
            <snapshots>  
                <enabled>true</enabled>  
            </snapshots>  
        </pluginRepository>  
        <pluginRepository>  
            <id>spring-milestones</id>  
            <name>Spring Milestones</name>  
            <url>https://repo.spring.io/milestone</url>  
            <snapshots>  
                <enabled>false</enabled>  
            </snapshots>  
        </pluginRepository>  
    </pluginRepositories>  
</project>  
 
  

// UserRecord.java

package com.javtpoint;  
import javax.persistence.Entity;  
import javax.persistence.Id;  
@Entity  
publicclass UserRecord {  
    @Id  
    privateintid;  
    private String name;  
    private String email;  
    public UserRecord(){}  
    publicint getId() {  
        returnid;  
    }  
    publicvoid setId(intid) {  
        this.id = id;  
    }  
    public String getName() {  
        returnname;  
    }  
    publicvoid setName(String name) {  
        this.name = name;  
    }  
    public String getEmail() {  
        returnemail;  
    }  
    publicvoid setEmail(String email) {  
        this.email = email;  
    }  
}  

// UserService.java

package com.javtpoint;  
import java.util.List;  
import java.util.Optional;  
import java.util.ArrayList;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  
@Service  
publicclass UserService {  
    @Autowired  
    private UserRepository userRepository;  
    public List<UserRecord> getAllUsers(){  
        List<UserRecord>userRecords = new ArrayList<>();  
        userRepository.findAll().forEach(userRecords::add);  
        returnuserRecords;  
    }  
    public Optional<UserRecord> getUser(String id){  
        returnuserRepository.findOne(id);  
    }  
    publicvoid addUser(UserRecord userRecord){  
        userRepository.save(userRecord);  
    }  
    publicvoid delete(String id){  
        userRepository.delete(id);  
    }  
}  

//UserController.java

package com.javtpoint;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RestController;  
import java.util.List;  
import java.util.Optional;  
@RestController  
publicclass UserController {  
    @Autowired  
    private UserService userService;   
    @RequestMapping("/")  
    public List<UserRecord> getAllUser(){  
        returnuserService.getAllUsers();  
    }     
    @RequestMapping(value="/add-user", method=RequestMethod.POST)  
    publicvoid addUser(@RequestBody UserRecord userRecord){  
        userService.addUser(userRecord);  
    }  
    @RequestMapping(value="/user/{id}", method=RequestMethod.GET)  
    public Optional<UserRecord> getUser(@PathVariable String id){  
        returnuserService.getUser(id);  
    }  
} 

// UserRepository.java

package com.javtpoint;  
import org.springframework.data.repository.CrudRepository;  
publicinterface UserRepository extends CrudRepository<UserRecord, String> {  
}  
 
  

// SpringBootJpaApplication.java

package com.javtpoint;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
@SpringBootApplication  
public class SpringBootJpaApplication {  
    public static void main(String[] args) {  
        SpringApplication.run(SpringBootJpaApplication.class, args);  
    }  
}  

Now run the applications

REFERENCE
SPRING BOOT JPA EXAMPLE
SPRING OFFICIAL



To view or add a comment, sign in

More articles by Karuna Mani

  • What is microservices and how Microservices Performed in Java

    Microservices have become hugely popular in recent years. Mainly, because they come with a couple of benefits that are…

  • Spring boot and Spring MVC Explained

    Spring Boot and Spring MVC are not comparable or mutually exclusive. If you want to do web application development…

  • Angular framework new features

    Angular 8 Updates And Summary of New Features is today’s topic. Angular 8 arrives with an impressive list of changes…

  • Top Open Source libraries for Java Programmers

    Here is my collection of some of the useful third-party libraries Java developers can use in their application to do a…

  • Linked List And Array In Java With Examples

    Difference between Linked List and Array in java is a popular interview question. This question is important for the…

  • How to compare two objects using java

    Java provides two mechanisms to compare objects: Using Comparable interface Using Comparator interface The purpose for…

  • How to convert Stream to Set using java

    In Java 8, Stream is one of the most important class as it allows a lot of useful functional operations e.g.

  • Java for the internet of things

    I’m sure most of you know what the revolutionary technology is all about. Thanks to IoT’s ability to connect with other…

  • learn java for better response to programming

    I’m a tutor of a Java course and I have many examples of people who started their studying Java at age 30 or even…

  • Choose java for developing web applications

    Inspired by C and C++ C and C++ are long-tenured programming languages and they are the ancestors of the modern…

Others also viewed

Explore content categories