几乎每一个应用,都需要连接数据库,所以我们使用Spring Data Jpa(下面简述jpa)+mysql来实现持久层。
我们以添加用户为例子。
1 添加依赖
compile('org.springframework.boot:spring-boot-starter-data-jpa') runtime('mysql:mysql-connector-java')
2 在application.properties中配置数据库信息
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
3 创建User的实体对象
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
private String id;
private String name;
private Integer age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
4 创建User的repository
public interface UserRepository extends PagingAndSortingRepository<User, String> {
}
5 添加userController
@RestController
public class UserController {
@Autowired
private UserRepository repository;
@RequestMapping(value = "/users", method = RequestMethod.POST)
public ResponseEntity createUser(@RequestBody User user) {
repository.save(user);
return ResponseEntity.ok().build();
}
@RequestMapping(value = "/users", method = RequestMethod.GET)
public ResponseEntity findAllUser() {
return ResponseEntity.ok(repository.findAll());
}
}
从上述代码能看到,我只需要创建一个接口UserRepository,不需要写额外的一行代码,就实现了save,findAll,findOne,delete等通用的CRUD的操作,这是jpa非常便利的一方面。
如果findAll和findOne都不满足查询需求,还可以自定义查询方法,例如
public interface UserRepository extends PagingAndSortingRepository<User, String> {
User findByName(String name);
}
关于自定义查询的更多详情,请查看jpa官方文档:
http://docs.spring.io/spring-data/jpa/docs/1.11.0.RELEASE/reference/html/#jpa.query-methods