The way to open Spring Boot: using JPA to get data

Posted by ljschrenk on Tue, 09 Jun 2020 06:16:14 +0200

1, Spring initialization

1. Open , fill in the relevant information of the project on this page, add the corresponding dependencies, and then click "GENERATE" to GENERATE a zip file, decompress it in a suitable location on your computer, and then open the project using IDEA.

2, Preparation of relevant documents

The effect to be achieved: store customer information (including ID, firstname, lastname) in H2 database, and get all customer information in the database, and get customer information according to customer ID and lastname. The specific implementation is as follows:

1. Define a simple Entity: create a customer class in the src/main/java/com/example/accessingdatajpa directory The code is as follows:

package com.example.accessingdatajpa;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

//This annotation indicates that Customer is a JPA entity, that is, it will map Customer to a table named Customer
public class Customer {

  //This annotation is intended to let JPA know that the ID attribute is the ID of the entity
  //This annotation indicates that the ID is auto plus 1
  private Long id;
  private String firstName;
  private String lastName;

  //JPA requires a default constructor
  protected Customer() {}

  //This constructor is what we use to create a Customer instance
  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

  //Override this method so that it can output Customer properties in a specific format
  public String toString() {
    return String.format(
        "Customer[id=%d, firstName='%s', lastName='%s']",
        id, firstName, lastName);

  public Long getId() {
    return id;

  public String getFirstName() {
    return firstName;

  public String getLastName() {
    return lastName;

2. Create a simple query: create a CustomerRepository interface under the directory "src/main/java/com/example/accessingdatajpa /"

package com.example.accessingdatajpa;

import java.util.List;


public interface CustomerRepository extends CrudRepository<Customer, Long> {

  List<Customer> findByLastName(String lastName);

  Customer findById(long id);

Explanation: Spring Data JPA can use JPA to store data in a relational database. The most significant feature is to automatically create implementation classes for the repository interface at runtime (you do not need to write their own implementation classes for the interface). CustomerRepository inherits from CrudRepository, so the interface contains save, delete and find methods. And you can customize other query methods, just declare the method in the interface, such as findByLastName() method in the code.

3. Create an application class: in the initialization phase, Spring Boot creates an AccessingDataJpaApplication class. The specific code is as follows:

package com.example.accessingdatajpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//This annotation indicates that this class is a SpringBoot application
public class AccessingDataJpaApplication {

  public static void main(String[] args) {
    //Use this method to start the SpringBoot application, args);

  public CommandLineRunner demo(CustomerRepository repository) {
    return (args) -> {
      // save a few customers Customer("Jack", "Bauer")); Customer("Chloe", "O'Brian")); Customer("Kim", "Bauer")); Customer("David", "Palmer")); Customer("Michelle", "Dessler"));

      // fetch all customers"Customers found with findAll():");"-------------------------------");
      for (Customer customer : repository.findAll()) {;

      // fetch an individual customer by ID
      Customer customer = repository.findById(1L);"Customer found with findById(1L):");"--------------------------------");;"");

      // fetch customers by last name"Customer found with findByLastName('Bauer'):");"--------------------------------------------");
      repository.findByLastName("Bauer").forEach(bauer -> {;
      // for (Customer bauer : repository.findByLastName("Bauer")) {
      // }"");


Explanation: demo method, first it will get the customer repository from the Spring application context, then store the customer information in the database, and then you can get the customer information you want according to some methods. Demo returns a CommandLineRunner bean that automatically runs its code when the application starts.

Topics: Spring Database Java SpringBoot