Getting Started

引导设置一个工作环境的简单方法是通过 start.spring.io 创建一个基于 Spring 的项目,或者在 Spring Tools 中创建一个 Spring 项目。

An easy way to bootstrap setting up a working environment is to create a Spring-based project via start.spring.io or create a Spring project in Spring Tools.

Examples Repository

GitHub spring-data-examples repository 托管了多个示例,您可以下载和试用它们来了解库的工作原理。

The GitHub spring-data-examples repository hosts several examples that you can download and play around with to get a feel for how the library works.

Hello World

让我们从一个简单的实体及其对应的存储库开始:

Let’s start with a simple entity and its corresponding repository:

@Entity
class Person {

  @Id @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  private String name;

  // getters and setters omitted for brevity
}

interface PersonRepository extends Repository<Person, Long> {

  Person save(Person person);

  Optional<Person> findById(long id);
}

创建要运行的主应用程序,如下所示:

Create the main application to run, as the following example shows:

@SpringBootApplication
public class DemoApplication {

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

  @Bean
  CommandLineRunner runner(PersonRepository repository) {
    return args -> {

      Person person = new Person();
      person.setName("John");

      repository.save(person);
      Person saved = repository.findById(person.getId()).orElseThrow(NoSuchElementException::new);
    };
  }
}

即使在这么简单的例子中,也有一些值得注意的事情:

Even in this simple example, there are a few notable things to point out:

  • Repository instances are automatically implemented. When used as parameters of @Bean methods, these will be autowired without further need for annotations.

  • The basic repository extends Repository. We suggest to consider how much API surface you want to expose towards your application. More complex repository interfaces are ListCrudRepository or JpaRepository.