在上一节的yml文件中,我们设置 ddl-auto 为 create,这会导致每一次启动项目的时候,都会去数据库里面重新创建表。这不是我们希望看到的,一般在项目开发中,我们更愿意把这个配置设置为update,这样的话,启动项目时它会去检测,如果表已经存在并且里面是有数据的,即不会去重新建表了。
server:
port: 8088
context-path: /demo
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/crud
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update
show-sql: true
我们需要使用spring-data-jpa来帮我们实现对用户表的增删改查,先去写一个接口,集成jpa:


package com.springboot.study.service;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springboot.study.bean.User;
public interface UserService extends JpaRepository<User, Integer>{
}
我们只需要写上类名和主键的类型,即可。

其他什么都不用写,就OK啦。
编写Controller:

代码:
package com.springboot.study.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.study.bean.User;
import com.springboot.study.service.UserService;
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
* 获取所有的用户列表
* @return
*/
@RequestMapping("findAllUsers")
public List<User> findAllUsers(){
return userService.findAll();
}
}
因为逻辑比较简单,我就直接给出一个例子了,启动项目,看结果。。
这次启动时间稍微长了一点:

浏览器输入:
http://localhost:8088/demo/findAllUsers
返回:

nice!
SpringBoot果然好用,一句sql都没写,甚至实现方法都没写,我们就完成了功能。
下载地址:http://java520.top/article/3db8d196-275b-41fa-98bf-69d173f0afc1.html
网友评论