在上一节的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都没写,甚至实现方法都没写,我们就完成了功能。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)