最近在往springboot框架上琢磨,于是便写了一个springboot整合mybatis的小demo。整个demo的需求就是简单的增删改查并没有多大的技术含量,但是通过写此demo的过程中深刻感受到springboot对开发的简化和“约定大于配置”的好处。
1.首先看一下项目的目录结构
1.config层
config层主要是写的对swagger-ui的一些配置信息。Swagger是最受欢迎的REST APIs文档生成工具之一,它是一个Restful风格接口的文档在线自动生成和测试的框架 。简单的理解就是使用它你可以一目了然的看见你写的接口是增删改查的哪一个。
package com.zg.springbootdemo.config; import com.google.common.base.Predicate; import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.RequestHandler; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /* * 在与spring boot集成时,放在与Application.java同级的目录下。 * 通过@Configuration注解,让Spring来加载该类配置。 * 再通过@EnableSwagger2注解来启用Swagger2。 * */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { Predicatepredicate = input -> { Class> declaringClass = input.declaringClass(); if (declaringClass == BasicErrorController.class)// 排除 return false; if(declaringClass.isAnnotationPresent(RestController.class)) // 被注解的类 return true; if(input.isAnnotatedWith(ResponseBody.class)) // 被注解的方法 return true; return false; }; return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select().apis(predicate) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() // 文档标题 .title("Spring Boot中使用Swagger2构建RESTful APIs") // 文档描述 .description("http://www.tianyigps.com") .termsOfServiceUrl("http://localhost:8080") .version("version 2.0.0") .contact(contact()) .build(); } private Contact contact() { return new Contact("@斑马", "http://www.baidu.com", "[email protected]"); } }
2. controller层。
该层使用了restful风格书写接口并使用了swagger。
restful风格有一个统一接口的规定,即CRUD(create, read, update和delete,即数据的增删查改)操作,分别对应于HTTP方法:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源,这样就统一了数据操作的接口,仅通过HTTP方法,就可以完成对数据的所有增删查改工作。完整代码如下:
package com.zg.springbootdemo.controller; import com.zg.springbootdemo.pojo.Demo; import com.zg.springbootdemo.pojo.User; import com.zg.springbootdemo.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.ibatis.annotations.Update; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.*; import javax.jws.soap.SOAPBinding; import java.util.List; import java.util.Optional; import java.util.Set; @RestController @RequestMapping("/user") /*value 就是描述作用 @Api:用在类上,说明该类的作用。 * */ @Api(value = "给用户提供增删改查的接口",description = "用户增删改查接口") public class UserController { @Autowired private UserService userService; @Autowired private RedisTemplate redisTemplate; /* * @ApiOperation:注解来给API增加方法说明。 * */ @GetMapping @ApiOperation(value = "查询用户", notes = "查询接口") public User findUser(int id,int r) { User user = userService.findUser(id); System.out.println(user); // redisTemplate.opsForValue().set("id",user); return user; } @PostMapping @ApiOperation(value = "增加用户",notes = "新增接口") public User insertUser(User user) { userService.insertUser(user); return user; } @PutMapping @ApiOperation(value = "更新用户信息",notes = "更新接口") public User updateUser(User user) { userService.updateUser(user); return user; } @DeleteMapping @ApiOperation(value = "删除用户",notes = "删除接口") public Integer deleteUser(@PathVariable Integer id) { userService.deleteUser(id); return id ; } @DeleteMapping("/delete") // Listids @ApiOperation(value = "删除多个用户",notes = "删除多个用户接口") public String deleteUser(Integer [] ids) { userService.deleteUserByList(ids); return "ok" ; } } 3 .mapper层
对数据库进行数据持久化操作,配置文件放在了resource目录下。
package com.zg.springbootdemo.Mapper; import com.zg.springbootdemo.pojo.User; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserMapper { User findUser(Integer id); List
findAllUser(User user); void insertUser(User user); void updateUser(User user); void deleteUser(Integer id); void deleteUserByList(Integer[] ids); }
4.pojo层
表的结构也很简单就三个字段id,name,age。
package com.zg.springbootdemo.pojo; public class User{ private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
5.service层
userService:
package com.zg.springbootdemo.service; import com.zg.springbootdemo.pojo.User; import java.util.List; public interface UserService { User findUser(Integer id); List
findAllUser(User user); void insertUser(User user); void updateUser(User user); void deleteUser(Integer id); void deleteUserByList(Integer[] ids); }
userServiceImpl:
package com.zg.springbootdemo.service; import com.zg.springbootdemo.Mapper.UserMapper; import com.zg.springbootdemo.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User findUser(Integer id) { User user = userMapper.findUser(id); return user; } @Override public List
findAllUser(User user) { return null; } @Override public void insertUser(User user) { userMapper.insertUser(user); } @Override public void updateUser(User user) { userMapper.updateUser(user); } @Override public void deleteUser(Integer id) { userMapper.deleteUser(id); } @Override public void deleteUserByList(Integer[] ids) { userMapper.deleteUserByList(ids); } }
6 .SpringbootdemoApplication
package com.zg.springbootdemo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication @ComponentScan(basePackages = {"com.zg.springbootdemo.*"}) @MapperScan("com.zg.springbootdemo.Mapper") public class SpringbootdemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootdemoApplication.class, args); } }
@ComponentScan注解会扫描对应包下面的所有注解。
@MapperScan注解是mybatis整个springboot的关键 ,通过使用@MapperScan可以指定要扫描的Mapper类的包的路径。
7.resource层
该层放置的是demo的配置文件,mapper层的配置文件也放在此处。
1.Usermapper的xml:
id, name, age, #{id}, #{name}, #{age}, INSERT INTO user( ) VALUES( ) UPDATE user WHERE id=#{id} age=#{age}, name=#{name}, delete from user where id in #{id} delete from user where id = #{id}
2.application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo spring.datasource.username=root spring.datasource.password=1234 spring.datasource.driverClassName=com.mysql.jdbc.Driver mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.zg.springbootdemo.pojo
maven如下 :
4.0.0 cn.zg springbootdemo 0.0.1-SNAPSHOT pom springbootdemo Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE UTF-8 UTF-8 1.8 Finchley.RC2 true org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-logging org.springframework.boot spring-boot-starter-log4j2 com.lmax disruptor 3.3.4 org.springframework.boot spring-boot-starter-web com.google.code.gson gson 2.8.4 org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-test test org.projectlombok lombok 1.16.18 org.springframework.boot spring-boot-starter-tomcat com.spatial4j spatial4j 0.5 org.springframework.boot spring-boot-starter-mail cn.zg springbootdemo 0.0.1-SNAPSHOT mysql mysql-connector-java 5.1.41 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 io.springfox springfox-swagger2 2.7.0 io.springfox springfox-swagger-ui 2.7.0 org.springframework.boot spring-boot-starter-data-redis spring-boot-parent org.apache.maven.plugins maven-compiler-plugin 3.3 ${java.version} ${java.version}
三、界面效果
项目全部写完之后启动,在浏览器输入http://localhost:8080/swagger-ui.html#/
整个界面如下: