SpringBoot JPA示例

x33g5p2x  于2022-10-06 转载在 Spring  
字(6.7k)|赞(0)|评价(0)|浏览(232)

在本教程中,我们将学习如何使用 **Spring Boot 和 JPA 创建基本应用程序。**我们将使用 Spring Boot CLI 创建应用程序,然后将其导入 IDE 以包含 JPA 类。

使用 CLI 创建 Spring Boot 应用程序

我们将从 Spring 命令行界面 开始。但是,如果您愿意,可以浏览Spring Initializr Web 应用程序。 – 在这方面请参阅本教程:使用 Spring Initializr 创建 Spring Boot 应用程序
在名为 samplewebapp 的 Web 应用程序中,我们需要以下依赖项:

$ spring init -dweb,data-jpa,h2   samplewebapp

接下来,让我们检查为我们创建的内容:

~/springboot:$ tree samplewebapp/
samplewebapp/
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── samplewebapp
    │   │               └── DemoApplication.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── com
                └── example
                    └── samplewebapp
                        └── DemoApplicationTests.java

这包含与 Initializr 基本相同的项目结构。它有一个 DemoApplication.java 类和一个 Test 类:

package com.example.samplewebapp;

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

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

这是项目的 pom.xml 文件中的依赖项列表:

<?xml version="1.0" encoding="UTF-8"?><project>
       
   <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>com.h2database</groupId>
                                  
         <artifactId>h2</artifactId>
                                  
         <scope>runtime</scope>
                          
      </dependency>
                       
      <dependency>
                                  
         <groupId>org.springframework.boot</groupId>
                                  
         <artifactId>spring-boot-starter-test</artifactId>
                                  
         <scope>test</scope>
                          
      </dependency>
               
   </dependencies>
</project>

在 IDE 中导入项目

接下来,我们将在您的 IDE 中导入 Maven 项目——(请参阅本文了解更多信息:选择用于 Spring Boot 开发的 IDE)

实际上,我们的应用程序不会做太多事情,所以让我们在名为 Person 的项目中添加一个 Entity

package com.example.samplewebapp;

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

@Entity
public class Person {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id;

  String name;
  String surname;

  public Person(String name, String surname) {
    super();
    this.name = name;
    this.surname = surname;
  }

  public Person() {
    super();
  }

  public Long getId() {
    return id;
  }

  private void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSurname() {
    return surname;
  }

  public void setSurname(String surname) {
    this.surname = surname;
  }

  @Override
  public String toString() {
    return "Person [id=" + id + ", name=" + name + ", surname=" + surname + "]";
  }
}

Spring 最酷的特性之一是能够在运行时从存储库接口自动创建存储库实现。开箱即用,存储库接口已经包含通过 id 查找实体和 findAll Entity 的方法。我们将在下面的 PersonRepository 接口中添加一个名为“findBySurname”的方法:

package com.example.samplewebapp;

import java.util.List;
import org.springframework.data.repository.CrudRepository;

public interface PersonRepository extends CrudRepository<Person, Long> {
  List<Person> findBySurname(String surname);
}

我们完成了后端。接下来,我们将在 @SpringBootApplication 类中添加一些逻辑来插入一些 Entity 对象并使用存储库接口检索它们:

package com.example.samplewebapp;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SpringBootApplication public class DemoApplication {
  private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
  @Bean public CommandLineRunner demo(PersonRepository repository) {
    return (args) -> { // save a couple of persons
      repository.save(new Person("Jack", "Smith"));
      repository.save(new Person("Joe", "Black"));
      repository.save(new Person("Martin", "Bauer")); 

      // fetch all persons
      log.info("Persons found with findAll():");
      for (Person person: repository.findAll()) {
        log.info(person.toString());
      }
      log.info(""); // fetch an individual person by ID
      repository.findById(1 L).ifPresent(person -> {
        log.info("Person found with findById(1L):");
        log.info("--------------------------------");
        log.info(person.toString());log.info("");
      });
        // fetch persons by last name
        log.info("Person found with findBySurname('Black'):");
        log.info("--------------------------------------------");
        repository.findBySurname("Black").forEach(smith -> {
        log.info(smith.toString());
      });log.info("");
    };
  }
}

如您所见,我们使用了 CommandLineRunner 接口来运行演示。事实上,Spring Boot 提供了两个接口,CommandLineRunnerApplicationRunner 在应用程序启动时运行特定的代码片段。一旦 SpringApplication 完成,这些接口就会在 run() 之前被调用。在我们的示例中使用的 CommandLineRunner 以字符串数组的形式提供对应用程序参数的访问。

添加 REST 控制器

我们可以通过添加一个控制器来进一步增强我们的应用程序,这将让我们检查存储库中可用的数据:

package com.example.samplewebapp;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonController {
  @Autowired PersonRepository repository;

  @RequestMapping("/list")
  public List<Person> findAll() {
    List<Person> list = new ArrayList<Person>();
    repository.findAll().iterator().forEachRemaining(list::add);
    return list;
  }

  @RequestMapping("/one/{id}")
  public Optional<Person> findOne(@PathVariable Long id) {
    return repository.findById(id);
  }
}

您可以直接从您的工具运行应用程序,例如,如果您使用带有 Spring Tools 的 Eclipse,右键单击 DemoApplication 类并选择 Run As > SpringBoot app

作为替代方案,只需运行:

mvn clean install spring-boot:run

或者:

java -jar target/samplewebapp-0.0.1-SNAPSHOT.jar

这是 SpringApplication 类提供的输出:

Persons found with findAll():
-------------------------------

Person [id=1, name=Jack, surname=Smith]
Person [id=2, name=Joe, surname=Black]
Person [id=3, name=Martin, surname=Bauer]

Person found with findById(1L):
--------------------------------
Person [id=1, name=Jack, surname=Smith]

Person found with findBySurname('Black'):
--------------------------------------------
Person [id=2, name=Joe, surname=Black]

您可以通过可用的Controller检查它,如下所示:

curl -s http://localhost:8080/list | jq [   {     "id": 1,     "name": "Jack",     "surname": "Smith"   },   {     "id": 2,     "name": "Joe",     "surname": "Black"   },   {     "id": 3,     "name": "Martin",     "surname": "Bauer"   } ]

和:

curl -s http://localhost:8080/one/1 | jq {   "id": 1,   "name": "Jack",   "surname": "Smith" }

在本教程中,我们学习了如何使用 Spring Boot** 和 JPA** 开发一个基本应用程序来存储一些数据并使用存储库类来检索它们。

源代码:https://github.com/fmarchioni/masterspringboot/tree/master/jpa/samplewebapp

相关文章

微信公众号

最新文章

更多