欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot 实现增删改查

程序员文章站 2022-06-21 14:38:59
创建项目bigdata先加载配置pom.xml

创建项目bigdata

spring 项目
eg
SpringBoot 实现增删改查
操作顺序
1.删除用不到的文件

SpringBoot 实现增删改查
将这个三个删除

2.先将app配置后缀名改为yml
3.然后创建entity这个包
4.创建dao包 这是跟数据库打交道的
5.再创建service包
6.创建controllern包
7.现在开始搞pom.xml文件
8.然后配置app.xml

SpringBoot 实现增删改查

先加载配置pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.nmgdz</groupId> <artifactId>bigdata</artifactId> <version>0.0.1-SNAPSHOT</version> <name>bigdata</name> <description>init project</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- druid数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!--lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--redis依赖配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--Swagger-UI API文档生产工具--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 

config包下面
Swagger2Config 配置

package com.nmgdz.bigdata.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /**
 作者: xhd
 创建时间: 2020/3/13 17:32
 版本: V1.0
 */ /**
 * Swagger2API文档的配置
 */ @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //为当前包下controller生成API文档 .apis(RequestHandlerSelectors.basePackage("com.nmgdz.bigdata.controller")) //为有@Api注解的Controller生成API文档 //                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //为有@ApiOperation注解的方法生成API文档 //                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("SwaggerUI演示") .description("内蒙古电子大数据工坊") .contact("xhd") .version("1.0") .build(); } } 

controller 包
IndexController配置

package com.nmgdz.bigdata.controller; import com.nmgdz.bigdata.entity.User; import com.nmgdz.bigdata.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; @Controller public class IndexController { @Autowired private UserService userService; @RequestMapping("/") public String index(ModelMap map) { //加入一个属性,用来在模板中读取 map.addAttribute("host", "内蒙古电子"); //return 模板文件的名称,对应src/main/resources/templates/index.html return "index"; } @RequestMapping("/echarts") public String echarts() { return "echarts"; } @RequestMapping("/echartx") public String echartx(ModelMap map) { List<User> users = userService.queryAll(); List<String> names = new ArrayList<>(); List<Integer> ages = new ArrayList<>(); if (users != null && users.size() > 0) { users.stream().forEach(user -> { names.add(user.getName()); ages.add(user.getAge()); }); } map.addAttribute("names",names); map.addAttribute("ages",ages); return "echartx"; } } 

UserController 配置

package com.nmgdz.bigdata.controller; import com.nmgdz.bigdata.entity.User; import com.nmgdz.bigdata.service.RedisService; import com.nmgdz.bigdata.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /**
 * @auther: xhd
 * @Date: 2020/9/1/11:15
 */ @RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; @Autowired private RedisService redisService; /**
     * 查询
     *
     * @param id
     * @return
     */ @GetMapping("/queryById") public User queryById(int id) { return userService.queryById(id); } /**
     * 增 改
     * @param user
     * @return
     */ @PostMapping("/saveOrUpdate") public User saveOrUpdateUser(User user) { return userService.save(user); } /**
     * 删除用户
     * @param id
     * @return
     */ @DeleteMapping("/delete") public Boolean deleteUser(int id) { userService.deletUserById(id); return true; } } 

在dao包
UserDao配置下

package com.nmgdz.bigdata.dao; import com.nmgdz.bigdata.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /**
 * 作者: xhd
 * 创建时间: 2020/3/12 19:51
 * 版本: V1.0
 */ public interface UserDao extends JpaRepository<User, Integer> { //List<User> findByAge(int age); User findById(int id); } 

在entity包
user配置

package com.nmgdz.bigdata.entity; import lombok.Data; import javax.persistence.*; @Table(name ="cc") @Entity @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private Integer age; 

在service包下
SpringBoot 实现增删改查
Impl包下
RedisServiceImpl

package com.nmgdz.bigdata.service; /**
 * @auther: xhd
 * @Date: 2020/9/2/0:26
 */ public interface RedisService { /**
     * 存储数据
     */ void set(String key, String value); /**
     * 获取数据
     */ String get(String key); /**
     * 设置超期时间
     */ boolean expire(String key, long expire); /**
     * 删除数据
     */ void remove(String key); /**
     * 自增操作
     *
     * @param delta 自增步长
     */ Long increment(String key, long delta); } 

UserServiceImpl

package com.nmgdz.bigdata.service.impl; import com.nmgdz.bigdata.dao.UserDao; import com.nmgdz.bigdata.entity.User; import com.nmgdz.bigdata.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /**
 * @auther: xhd
 * @Date: 2020/9/1/11:12
 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; //    @Override //    public List<User> queryByAge(int age) { //        return userDao.findByAge(age); //    } //    @Override //    public List<User> queryByAge(int age) { //        return null; //    } @Override public User save(User user) { return userDao.save(user); } @Override public void deletUserById(int id) { userDao.deleteById(id); } @Override public User queryById(int id) { return userDao.findById(id); } @Override public List<User> queryAll() { return userDao.findAll(); } } 

RedisService

package com.nmgdz.bigdata.service; /**
 * @auther: xhd
 * @Date: 2020/9/2/0:26
 */ public interface RedisService { /**
     * 存储数据
     */ void set(String key, String value); /**
     * 获取数据
     */ String get(String key); /**
     * 设置超期时间
     */ boolean expire(String key, long expire); /**
     * 删除数据
     */ void remove(String key); /**
     * 自增操作
     *
     * @param delta 自增步长
     */ Long increment(String key, long delta); } 

UserService

package com.nmgdz.bigdata.service; import com.nmgdz.bigdata.entity.User; import java.util.List; /**
 * @auther: xhd
 * @Date: 2020/9/1/11:10
 */ public interface UserService { /**
     * 根据年龄查询用户
     *
     * @param age
     * @return
     */ // List<User> queryByAge(int age); /**
     * 保存用户
     *
     * @param user
     * @return
     */ User save(User user); /**
     * 根据主键删除用户
     *
     * @param id
     */ void deletUserById(int id); /**
     * 根据主键查询
     * @param id
     * @return
     */ User queryById(int id); /**
     * 查询所有
     * @return
     */ List<User> queryAll(); } 

BigdataApplication配置下

package com.nmgdz.bigdata; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BigdataApplication { public static void main(String[] args) { SpringApplication.run(BigdataApplication.class, args); } } 

SpringBoot 实现增删改查

在templates下
echarts.html

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>Spring Boot中使用ECharts</title> <script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script> </head> <body> <div id="main" style="width: 1000px;height:400px;"></div> </body> <script type="text/javascript"> let myChart = echarts.init(document.getElementById('main')); let option = { title: { text: 'Spring Boot中使用ECharts' }, tooltip: {}, xAxis: { data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: {}, series: [{ data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line' }]}; // option = { //     xAxis: { //       type: 'category', //        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] //     }, //    yAxis: { //         type: 'value' //     }, //     series: [{ //         data: [120, 200, 150, 80, 70, 110, 130], //         type: 'bar', //         showBackground: true, //        backgroundStyle: { //             color: 'rgba(220, 220, 220, 0.8)' //      } //     }] // }; myChart.setOption(option); </script> </html> 

echartx.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Title</title> <script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script> </head> <body> <div id="main" style="width: 1000px;height:400px;"></div> </body> <script type="text/javascript" th:inline="javascript"> let myChart=echarts.init(document.getElementById('main')); let option = { title: { text:'Spring Boot中使用ECharts' }, tooltip: {}, xAxis: { type: 'category', data: [[${names}]] }, yAxis: { type: 'value' }, series: [{ data: [[${ages}]], type: 'line' }] }; myChart.setOption(option); </script> </html> 

index.html

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title></title> </head> <body> <h1 th:text="${host}">Hello World</h1> </body> </html> 

application.yml

spring: datasource: type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai
    username: root
    password: 123456 initialSize: 20 minIdle: 50 maxActive: 500 jpa: hibernate: ddl-auto: update
    show-sql: true redis: host: localhost # Redis服务器地址
    database: 0 # Redis数据库索引(默认为0)
    port: 6379 # Redis服务器连接端口
    password: 123456 # Redis服务器连接密码(默认为空)
    jedis: pool: max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 8 # 连接池中的最大空闲连接
        min-idle: 0 # 连接池中的最小空闲连接
    timeout: 3000ms # 连接超时时间(毫秒) 

Test是数据库名字
User 里面的cc是数据库

SpringBoot 实现增删改查

测试方法
SpringBoot 实现增删改查

BigdataApplicationTests

package com.nmgdz.bigdata; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class BigdataApplicationTests { @Test void contextLoads() { } } 

RedisTest

package com.nmgdz.bigdata; import com.nmgdz.bigdata.service.RedisService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; /**
 * @auther: xhd
 * @Date: 2020/9/2/0:28
 */ @Slf4j @SpringBootTest public class RedisTest { @Autowired private RedisService redisService; //TODO main函数测试 @Test public void testRedis(){ redisService.set("dianzi","123456"); System.out.println("设置得值为---"+redisService.get("dianzi")); } } 

http://localhost:8080/swagger-ui.html
增删改查

SpringBoot 实现增删改查

增删改查
在postm里面实现
GET http://localhost:8080/user/queryById?id=1
查询

SpringBoot 实现增删改查

在 POST
http://localhost:8080/user/saveOrUpdate?id=1&name=jeu&age=18
修改

SpringBoot 实现增删改查

删除
delete http://localhost:8080/user/delete?id=1

SpringBoot 实现增删改查

可视化页面
http://localhost:8080/echartx

SpringBoot 实现增删改查

本文地址:https://blog.csdn.net/qq_45235750/article/details/108759786

相关标签: spring boot