开始
一个简单的启动工作环境搭建方法是通过 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);
};
}
}
即使在这个简单的例子中,也有几点值得注意:
-
仓库实例是自动实现的。 当用作
@Bean方法,这些将自动布线,无需额外注释。 -
基础仓库扩展
存储 库. 我们建议考虑你希望为应用暴露多少API表面。 更复杂的存储库接口包括ListCrudRepository或JpaRepository.