Springboot对mysql数据库进行增删改查操作

tech2024-07-08  61

一、创建Springboot项目并创建包、class、interface。如图所示 1.1各个class和interface文件中的代码 User:

package com.example.demo.entity import lombok.Data; import org.hibernate.annotations.CreationTimestamp; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; @Table(name ="company") @Entity @Data public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String company_code; private Boolean monitor_type; private String sys_name; private Integer equipment_type_id; private String equipment_type_name; private Integer sensor_type_id; private String sensor_type_name; private Integer technology_type_id; private String technology_type_name; private String department; private String sensor_code; private String location; private String storage_material; private BigDecimal level_alarm_high; private BigDecimal secondary_alarm_high; private BigDecimal level_alarm_low; private BigDecimal secondary_alarm_low; private Integer operate_id; private String operate_username; @CreationTimestamp @Column(name="create_time") @DateTimeFormat(pattern = "yyyy-mm-dd") private Date create_time; @CreationTimestamp @Column(name="update_time") @DateTimeFormat(pattern = "yyyy-mm-dd") private Date update_time; } }

UserDao:

package com.example.demo.dao; import com.example.demo.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface UserDao extends JpaRepository<User,Integer> { List<User> findById(int id);

UserService:

package com.example.demo.service; import com.example.demo.entity.User; import java.util.List; public interface UserService { /** * 根据查询用户 * @return */ // List<User> queryByTypeid(int typed); /** * 保存用户 * @param user * @return */ User save(User user); /** * 根据主键删除用户 * @param id */ void deletUserById(int id); /** * 根据主键查询 * @param id * @return */ User queryById(int id); }

UserController:

package com.example.demo.controller; import com.example.demo.entity.User; import com.example.demo.service.RedisService; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; @Autowired private RedisService redisService; @GetMapping("/queryById") public String queryById(Integer id) { String userStr = redisService.get(id + ""); if (userStr == null) { redisService.set(id + "", userService.queryById(id).toString()); return userService.queryById(id).toString(); } return userStr; } /** * 增 改 * * @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; } }

RedisService:

package com.example.demo.service; public interface RedisService { /** * 储存数据 * @param key * @param value */ void set(String key, String value); /** * 获取数据 * @param key * @return */ String get(String key); /** * 设置超期时间 * @param key * @param expire * @return */ boolean expire(String key, long expire); /** * 删除数据 * @param key */ void remove(String key); /** * 自增操作 * @param key * @param delta 自增步长 * @return */ Long incream(String key, long delta); void findOne(String key); }

UserServiceImpl:

package com.example.demo.service.impl; import com.example.demo.dao.UserDao; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; // @Override // public List<User> queryByTypeid(int typeid) { // return userDao.findById(typeid); // } @Override public User save(User user) { return userDao.save(user); } @Override public void deletUserById(int id) { } @Override public User queryById(int id) { return userDao.getOne(id); } }

RedisServiceImpl:

package com.example.demo.service.impl; import com.example.demo.service.RedisService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service public class RedisServiceImpl implements RedisService { @Autowired private StringRedisTemplate stringRedisTemplate; @Override public void set(String key, String value) { stringRedisTemplate.opsForValue().set(key,value); } @Override public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } @Override public boolean expire(String key, long expire) { return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS); } @Override public void remove(String key) { stringRedisTemplate.delete(key); } @Override public Long incream(String key, long delta) { return stringRedisTemplate.opsForValue().increment(key, delta); } @Override public void findOne(String key) { } }

Swagger2Config:

package com.example.demo.config; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; 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; import java.lang.annotation.Documented; @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //为当前包下controller生成API文档 .apis(RequestHandlerSelectors.basePackage("com.example.demo.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("ZS") .version("1.0") .build(); } }

导入依赖:pom.xml

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </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-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> <!--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-data-redis</artifactId> </dependency>

application.yml: //后缀名手动修改为.yml

spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&charactEnoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai username: root password: 123456 initiaSize: 20 minIdle: 50 maxActive: 500 jpa: hibernate: ddl-auto: update show-sql: true

如果redis有密码的设置,则在此声明。 关于redis操作在“安装redis”博文中介绍。 点击运行,结果如图: 数据库表如图 在网页搜索:http://localhost:8080/swagger-ui.html 在此页面测试是否可以对表进行操作 以增加为例结果如图:

再次查看表(记得刷新) 或者用Postman软件,输入网址:http://localhost:8080/user/queryById?id=1

表示成功。 写博文容易,其中问题层出不穷,解决问题才能进步!!!!!!!!!

最新回复(0)