随笔 - 434,  文章 - 0,  评论 - 463,  阅读 - 46万

在上一节的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都没写,甚至实现方法都没写,我们就完成了功能。

posted on   剽悍一小兔  阅读(57)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示