跳到主要内容
版本:4.1.1

快速上手

Doubao 中英对照 Getting Started

通过 start.spring.io 创建一个基于 Spring 的项目,或在 Spring Tools 中创建一个 Spring 项目,是搭建可用环境的简便方式。

示例仓库​

GitHub 上的 spring-data-examples 仓库 托管了若干示例,您可以下载并动手尝试,以感受该库的工作方式。

Hello World​

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

@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);
}

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

@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);
};
}
}

即使在这个简单的示例中,也有几点值得指出:

  • 仓库实例会被自动实现。当用作 @Bean 方法的参数时,它们会被自动装配,无需额外注解。

  • 基础仓库继承 Repository。我们建议您考虑希望向应用程序暴露多大的 API 表面。更复杂的仓库接口有 ListCrudRepository 或 JpaRepository。