快速开始
一种快速搭建工作环境的简便方法是通过 start.spring.io 创建一个基于 Spring 的项目,或在 Spring Tools 中创建一个 Spring 项目。
示例仓库
GitHub 上的 spring-data-examples 仓库 提供了多个示例,您可以下载并试用这些示例,以了解该库的工作方式。
你好,世界
让我们从一个简单的实体及其对应的仓库开始:
@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);
};
}
}
即使在这个简单的示例中,也有几点值得注意的地方:
-
Repository 实例会自动实现。 当用作
@Bean方法的参数时,这些实例将自动装配,无需额外添加注解。 -
基础仓库接口继承自
Repository。 我们建议您考虑要向应用程序暴露多少 API 接口。 更复杂的仓库接口包括ListCrudRepository或JpaRepository。