龙空技术网

SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查

码匠心 117

前言:

现时咱们对“使用druid连接数据库实现对站点信息的增删改查”可能比较重视,兄弟们都需要分析一些“使用druid连接数据库实现对站点信息的增删改查”的相关知识。那么小编同时在网上搜集了一些有关“使用druid连接数据库实现对站点信息的增删改查””的相关知识,希望朋友们能喜欢,咱们一起来了解一下吧!

前言

Spring boot项目目前是Java Web开发领域最受市场欢迎的Spring框架之一,也是构建分布式项目、微服务项目重要基础之一,Spring Boot免去了配置繁杂的依赖和配置,使得开发人员把更多的精力放在项目本身上,就Spring框架而言,Spring Boot可谓是集大成者,担负着敏捷开发,前后台分离、模块低耦合的神圣使命;麻将哥也是一个忠实的SpringBoot fans,这篇教程零基础的带大家从新建项目开始,完成一个流程的CRUD。本教程采用Spring Boot+Mybatis+Mysql实现,麻将哥MySql的版本是5.7,建议大家的Mysql是5.7或者5.7+。

准备工作

编辑器:InteIIiJ IDEA

MySql数据库表设计:

IDEA新建Spring Boot 项目这篇文章就不再赘述,需要的小伙伴可以查看麻将哥的上一篇文章。

构建项目使用IDEA新建项目后,目录结构如下:

2.在curddemo目录新建5个package,分别为bean,config,controller,mapper,service,bean主要用来放置实体类文件,config要来放置放置Swagger接口文档的配置类文件,controller用来放置程序控制器(API)类文件,service用来放置处理业务逻辑的类文件,mapper用来放置于数据库映射相关的类文件。建成项目目录如下:

3.在pom.xml文件下添加以下依赖:

<?xml version="1.0" encoding="UTF-8"?><project xmlns="" xmlns:xsi="" xsi:schemaLocation=" "> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.yisio</groupId> <artifactId>curddemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>curddemo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- druid数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build></project>

4.在resources目录的application.properties文件里配置mysql连接信息:

#Created by 码匠心 on 2019/10/05.#MySQL配置spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo?serverTimezone=UTC&characterEncoding=UTF-8spring.datasource.username=rootspring.datasource.password=root#MyBatis日志配置mybatis.config-location=classpath:/mybatis-config.xml#端口配置server.port=8080

5.在resources目录下新建mybatis日志文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" ""><configuration> <settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings></configuration>

6.在bean目录下新建实体类User.java

/** * Created by 码匠心 on 2019/10/05. */public class User { public Integer UserId; public String UserName; public boolean Sex; public boolean Wedlock; public String Place; public void setUserId(Integer UserId){this.UserId=UserId;} public void setUserName(String UserName){this.UserName=UserName;} public void setSex(boolean Sex){this.Sex=Sex;} public void setWedlock(boolean Wedlock){this.Wedlock=Wedlock;} public void setPlace(String Place){this.Place=Place;}}

7.在config目录下新建Swagger在线接口文档的配置文SwaggerConfig.java

@Configuration@EnableSwagger2public class SwaggerConfig { @Bean public Docket api(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() //文档标题 .title(" Spring Boot RESTful API") // 版本号 .version("1.0") // 标题描述 .description("swagger在线文档") .build(); } }

8.在mapper目录下新建UserMapper接口文件,新建增删改查的四个方法

/** * Created by 码匠心 on 2019/10/05. */import java.util.List;@Mapperpublic interface UserMapper { List<User> getAllUser(); int AddUser(User users); int updateUser(@Param("users") User users); int deleteUserByUserId(@Param("ids") String[] ids);}

9.在mapper目录下新建UserMapper.xml文件,使用mybtis操作数据库

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" ""><mapper namespace="com.yisio.curddemo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.yisio.curddemo.bean.User"> <result column="UserId" property="UserId"/> <result column="UserName" property="UserName"/> <result column="Sex" property="Sex"/> <result column="Wedlock" property="Wedlock"/> <result column="Place" property="Place"/> </resultMap> <select id="getAllUser" resultMap="BaseResultMap"> select * from sysuser; </select> <insert id="AddUser" parameterType="com.yisio.curddemo.bean.User"> insert into sysuser(UserName,Sex,Wedlock,Place) values(#{UserName,jdbcType=VARCHAR}, #{Sex,jdbcType=BOOLEAN}, #{Wedlock,jdbcType=BOOLEAN}, #{Place,jdbcType=VARCHAR}) </insert> <update id="updateUser"> update sysuser <set> UserName=#{users.UserName,jdbcType=VARCHAR}, Sex=#{users.Sex,jdbcType=BOOLEAN}, Wedlock=#{users.Wedlock,jdbcType=BOOLEAN}, Place=#{users.Place,jdbcType=VARCHAR} </set> where UserId=#{users.UserId,jdbcType=INTEGER} </update> <delete id="deleteUserByUserId"> DELETE from sysuser where UserId in <foreach collection="ids" separator="," open="(" close=")" item="id"> #{id} </foreach> </delete></mapper>

10.在service目录下新建业务逻辑类UserService.java

/** * Created by 码匠心 on 2019/10/05. */@Service@Transactionalpublic class UserService { @Autowired UserMapper userMapper; public List<User> getAllUser(){ return userMapper.getAllUser(); } private void UserDo(User users) { users.setUserId(users.UserId); users.setUserName(users.UserName); users.setPlace(users.Place); users.setSex(users.Sex); users.setWedlock(users.Wedlock); } public int AddUser(User users) { UserDo(users); return userMapper.AddUser(users); } public int updateUser(User users){ UserDo(users); return userMapper.updateUser(users); } public boolean deleteUserByUserId(String ids){ String[] split = ids.split(","); return userMapper.deleteUserByUserId(split) == split.length; }}

11.在controller目录下新建业务接口类UserController.java

/** * Created by 码匠心 on 2019/10/05. */@RestController@RequestMapping("/User/UserData")@Api(value = "UserController",description = "用户管理")public class UserController { @Autowired UserService userService; @ApiOperation(value = "用户查询") @RequestMapping(value = "/UserData",method = RequestMethod.GET) public Map<String,Object> getAllUser(){ Map<String,Object> map=new HashMap<>(); map.put("User",userService.getAllUser()); return map; } @ApiOperation(value = "新增用户") @RequestMapping(value = "/UserData/AddUser",method = RequestMethod.POST) public String AddUser(User users) { if (userService.AddUser(users)==1) return "新增成功!"; return "新增失败!"; } @ApiOperation(value = "修改用户") @RequestMapping(value = "/UserData/updateUser",method = RequestMethod.PUT) public String updateUser(User users){ if (userService.updateUser(users)==1) return "修改成功!"; return "修改失败!"; } @ApiOperation(value = "删除用户") @RequestMapping(value = "/UserData/deleteUser/{ids}",method = RequestMethod.DELETE) public String deleteUserByUserId(@PathVariable String ids){ if(userService.deleteUserByUserId(ids)) return "删除成功!"; return "删除失败!"; }}

12.最后的项目结构如下:

13.点击右上角项目启动按钮,运行项目,启动窗口看到如下信息则说明项目启动成功

14.在浏览器里输入URL:;结果界面如下:

到这里我们的项目就启动成功了,执行Swagger接口文档里面的各个接口就能执行相应的增删改查操作!

标签: #使用druid连接数据库实现对站点信息的增删改查