大家好,我是架構君,一個會寫代碼吟詩的架構師。今天說一說使用springboot + druid + mybatisplus完成多資料源配置「建議收藏」,希望能夠幫助大家進步!!!
一. 簡介
1. 版本
springboot版本為2.0.3.RELEASE,mybatisplus版本為2.1.9, druid版本為1.1.9,swagger版本為2.7.0
2. 項目位址
https://gitee.com/wbsxch/ssm.git
該位址有初始sql和測試方法
3. 留個記錄,友善查找
開發步驟:
1. 建立springboot項目。
2. 導入依賴 --> devtools,lombok,web,thymeleaf,mysql,aop,mybatisplus,druid,swagger。
3. maven多環境配置。
4. 編寫application.yml --> 項目端口,項目路徑名,mybatisplus配置,mysql多資料源配置。
5. 建立DataSourceContextHolder 用于設定,擷取,清空 目前線程内的資料源變量。
6. 建立 MultipleDataSource 實作 AbstractRoutingDataSource 類。重寫determineCurrentLookupKey(),通過
DataSourceContextHolder 擷取資料源變量,用于當作lookupKey取出指定的資料源。
7. 建立DataSourceEnum 用于存放資料源名稱。
8. 建立注解 DataSource,用于aop類中當作切入點來選擇資料源。編寫aop類 --> DataSourceAspect.java
9. 建立并配置DruidConfiguration,MybatisplusConfiguration,SwaggerConfiguration 三個類。DruidConfiguration --> StatViewServlet 和 WebStatFilter Druid監控配置和監控過濾器MybatisplusConfiguration --> mybatisplus 分頁插件,SQL執行效率插件資料源Bean,MultipleDataSource 注入SqlSessionFactory注入SwaggerConfiguration --> 正常配置。
10. crud Controller接口。
11. 完整項目結構

二. 詳細步驟
1. 建立springboot項目
idea建立Empty項目 然後建立springboot項目 勾選 devtools,lombok,web,thymeleaf,mysql
2. 導入依賴
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.seawaterbt</groupId>
<artifactId>ssm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ssm</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<druid.version>1.1.9</druid.version>
<swagger.version>2.7.0</swagger.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-devtools</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>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.1.9</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
<profiles>
<profile>
<id>prod</id>
<properties>
<config.dir>prod</config.dir>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<config.dir>dev</config.dir>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>qa</id>
<properties>
<config.dir>qa</config.dir>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources/config/${config.dir}</directory>
<includes>
<include>*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources/</directory>
</resource>
</resources>
</build>
</project>
複制
3. Maven多環境配置 看pom檔案
4. 編寫application.yml
server:
port: 8080
servlet:
context-path: /ssm
spring:
datasource:
druid:
db1:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///mds
initialSize: 5
minIdle: 5
maxActive: 20
db2:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///ssj
initialSize: 5
minIdle: 5
maxActive: 20
mybatis-plus:
# 如果是放在src/main/java目錄下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
# 如果是放在resource目錄 classpath:/mapper/*Mapper.xml
mapper-locations: classpath:/mapper/*Mapper.xml
#實體掃描,多個package用逗号或者分号分隔
typeAliasesPackage: com.seawatebt.ssm.entity
global-config:
#主鍵類型 0:"資料庫ID自增", 1:"使用者輸入ID",2:"全局唯一ID (數字類型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段政策 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
field-strategy: 2
#駝峰下劃線轉換
db-column-underline: true
#mp2.3+ 全局表字首 mp_
#table-prefix: mp_
#重新整理mapper 調試神器
refresh-mapper: true
#資料庫大寫下劃線轉換
#capital-mode: true
#邏輯删除配置(下面3個配置)
logic-delete-value: 4
logic-not-delete-value: 0
configuration:
#配置傳回資料庫(column下劃線命名&&傳回java實體是駝峰命名),自動比對無需as(沒開啟這個,SQL需要寫as: select user_id as userId)
map-underscore-to-camel-case: true
cache-enabled: false
#配置JdbcTypeForNull, oracle資料庫必須配置
jdbc-type-for-null: 'null'
複制
5. 建立DataSourceContextHolder
package com.seawaterbt.ssm.multiple;
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
/**
* 設定資料源
* @param db
*/
public static void setDataSource(String db){
contextHolder.set(db);
}
/**
* 取得目前資料源
* @return
*/
public static String getDataSource(){
return contextHolder.get();
}
/**
* 清除上下文資料
*/
public static void clear(){
contextHolder.remove();
}
}
複制
6. 建立 MultipleDataSource
package com.seawaterbt.ssm.multiple;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class MultipleDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}
複制
7. 建立DataSourceEnum
package com.seawaterbt.ssm.enums;
public enum DataSourceEnum {
DB1("db1"),DB2("db2");
private String value;
DataSourceEnum(String value){this.value=value;}
public String getValue() {
return value;
}
}
複制
8. 建立注解 DataSource
package com.seawaterbt.ssm.annotation;
import com.seawaterbt.ssm.enums.DataSourceEnum;
import java.lang.annotation.*;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
DataSourceEnum value() default DataSourceEnum.DB1;
}
複制
@Component
@Slf4j
@Aspect
@Order(-1)
public class DataSourceAspect {
@Pointcut("@within(com.seawaterbt.ssm.annotation.DataSource) || @annotation(com.seawaterbt.ssm.annotation.DataSource)")
public void pointCut(){
}
@Before("pointCut() && @annotation(dataSource)")
public void doBefore(DataSource dataSource){
log.info("選擇資料源---"+dataSource.value().getValue());
DataSourceContextHolder.setDataSource(dataSource.value().getValue());
}
@After("pointCut()")
public void doAfter(){
DataSourceContextHolder.clear();
}
}
複制
9. 建立并配置DruidConfiguration,MybatisplusConfiguration,SwaggerConfiguration
package com.seawaterbt.ssm.config;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DruidConfiguration {
@Bean
public ServletRegistrationBean startViewServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
// IP白名單
servletRegistrationBean.addInitParameter("allow","127.0.0.1");
// IP黑名單(共同存在時,deny優先于allow)
servletRegistrationBean.addInitParameter("deny","127.0.0.1");
//控制台管理使用者
servletRegistrationBean.addInitParameter("loginUsername","admin");
servletRegistrationBean.addInitParameter("loginPassword","123456");
//是否能夠重置資料
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean statFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//添加過濾規則
filterRegistrationBean.addUrlPatterns("/*");
//忽略過濾的格式
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
複制
package com.seawaterbt.ssm.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.seawaterbt.ssm.enums.DataSourceEnum;
import com.seawaterbt.ssm.multiple.MultipleDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@MapperScan("com.seawaterbt.ssm.mapper*")
public class MyBatiesPlusConfiguration {
/*
* 分頁插件,自動識别資料庫類型
* 多租戶,請參考官網【插件擴充】
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 開啟 PageHelper 的支援
paginationInterceptor.setLocalPage(true);
return paginationInterceptor;
}
/**
* SQL執行效率插件
*/
@Bean
@Profile({"dev","qa"})// 設定 dev test 環境開啟
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000);
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1" )
public DataSource db1() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2" )
public DataSource db2() {
return DruidDataSourceBuilder.create().build();
}
/**
* 動态資料源配置
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource(@Qualifier("db1") DataSource db1, @Qualifier("db2") DataSource db2) {
MultipleDataSource multipleDataSource = new MultipleDataSource();
Map< Object, Object > targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceEnum.DB1.getValue(), db1);
targetDataSources.put(DataSourceEnum.DB2.getValue(), db2);
//添加資料源
multipleDataSource.setTargetDataSources(targetDataSources);
//設定預設資料源
multipleDataSource.setDefaultTargetDataSource(db1);
return multipleDataSource;
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(db1(),db2()));
//sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*/*Mapper.xml"));
MybatisConfiguration configuration = new MybatisConfiguration();
//configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
sqlSessionFactory.setPlugins(new Interceptor[]{ //PerformanceInterceptor(),OptimisticLockerInterceptor()
paginationInterceptor() //添加分頁功能
});
//sqlSessionFactory.setGlobalConfig(globalConfiguration());
return sqlSessionFactory.getObject();
}
/*@Bean
public GlobalConfiguration globalConfiguration() {
GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
conf.setLogicDeleteValue("-1");
conf.setLogicNotDeleteValue("1");
conf.setIdType(0);
//conf.setMetaObjectHandler(new MyMetaObjectHandler());
conf.setDbColumnUnderline(true);
conf.setRefresh(true);
return conf;
}*/
}
複制
package com.seawaterbt.ssm.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.seawaterbt.ssm.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("多資料源 SSM 測試服務")
.description("多資料源 SSM 測試文檔")
.termsOfServiceUrl("http://www.seawaterbt.com")
//.contact(new Contact("海水不甜","http://www.seawaterbt.com","[email protected]"))
.version("1.0")
.build();
}
}
複制
10. crud Controller接口
1. Entity
package com.seawaterbt.ssm.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Api("學生實體對象")
@Data
@TableName("t_student")
public class Student {
@ApiModelProperty("學生id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("學生姓名")
private String name;
@ApiModelProperty("學生年齡")
private Integer age;
@ApiModelProperty("學生班級")
private String classname;
}
複制
package com.seawaterbt.ssm.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Api("老師實體對象")
@Data
@TableName("t_teacher")
public class Teacher {
@ApiModelProperty("老師id")
@TableId(type = IdType.AUTO)
private Integer id;
@ApiModelProperty("老師姓名")
private String name;
@ApiModelProperty("老師年齡")
private Integer age;
@ApiModelProperty("老師所教學科")
private String subject;
}
複制
2. Mapper 接口及其xml
package com.seawaterbt.ssm.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.seawaterbt.ssm.entity.Student;
public interface StudentMapper extends BaseMapper<Student> {
}
複制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.seawaterbt.ssm.mapper.StudentMapper">
</mapper>
複制
package com.seawaterbt.ssm.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.seawaterbt.ssm.entity.Teacher;
public interface TeacherMapper extends BaseMapper<Teacher> {
}
複制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.seawaterbt.ssm.mapper.TeacherMapper">
</mapper>
複制
3. Service 接口及其實作類
package com.seawaterbt.ssm.service;
import com.baomidou.mybatisplus.service.IService;
import com.seawaterbt.ssm.entity.Student;
public interface StudentService extends IService<Student> {
}
複制
package com.seawaterbt.ssm.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.seawaterbt.ssm.entity.Student;
import com.seawaterbt.ssm.mapper.StudentMapper;
import com.seawaterbt.ssm.service.StudentService;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> implements StudentService {
}
複制
package com.seawaterbt.ssm.service;
import com.baomidou.mybatisplus.service.IService;
import com.seawaterbt.ssm.entity.Teacher;
public interface TeacherService extends IService<Teacher> {
}
複制
package com.seawaterbt.ssm.service.impl;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.seawaterbt.ssm.annotation.DataSource;
import com.seawaterbt.ssm.entity.Teacher;
import com.seawaterbt.ssm.enums.DataSourceEnum;
import com.seawaterbt.ssm.mapper.TeacherMapper;
import com.seawaterbt.ssm.service.TeacherService;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper,Teacher> implements TeacherService {
@Override
@DataSource(DataSourceEnum.DB2)
public boolean insert(Teacher entity) {
return super.insert(entity);
}
@Override
@DataSource(DataSourceEnum.DB2)
public boolean deleteById(Serializable id) {
return super.deleteById(id);
}
@Override
@DataSource(DataSourceEnum.DB2)
public boolean updateById(Teacher entity) {
return super.updateById(entity);
}
@Override
@DataSource(DataSourceEnum.DB2)
public Teacher selectById(Serializable id) {
return super.selectById(id);
}
@Override
@DataSource(DataSourceEnum.DB2)
public List<Teacher> selectList(Wrapper<Teacher> wrapper) {
return super.selectList(wrapper);
}
@Override
@DataSource(DataSourceEnum.DB2)
public Page<Teacher> selectPage(Page<Teacher> page) {
return super.selectPage(page);
}
@Override
@DataSource(DataSourceEnum.DB2)
public Page<Teacher> selectPage(Page<Teacher> page, Wrapper<Teacher> wrapper) {
return super.selectPage(page, wrapper);
}
}
複制
4. Vo
package com.seawaterbt.ssm.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("學生vo")
public class StudentVo {
@ApiModelProperty("學生姓名")
private String name;
@ApiModelProperty("學生年齡")
private Integer age;
@ApiModelProperty("學生班級")
private String classname;
}
複制
package com.seawaterbt.ssm.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("老師vo")
public class TeacherVo {
@ApiModelProperty("老師姓名")
private String name;
@ApiModelProperty("老師年齡")
private Integer age;
@ApiModelProperty("老師教的學科")
private String subject;
}
複制
5. Controller
package com.seawaterbt.ssm.controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.seawaterbt.ssm.entity.Student;
import com.seawaterbt.ssm.service.StudentService;
import com.seawaterbt.ssm.vo.StudentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api("對學生表CRUD")
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@ApiOperation("添加學生")
@PostMapping("/add")
public String add(@RequestBody StudentVo student){
Student stu = new Student();
stu.setName(student.getName());
stu.setAge(student.getAge());
stu.setClassname(student.getClassname());
return studentService.insert(stu)?"添加成功":"添加失敗";
}
@ApiOperation("删除學生")
@DeleteMapping("/delete/{id}")
public String delete(@ApiParam("學生的主鍵id")@PathVariable(value = "id") Integer id){
return studentService.deleteById(id)?"删除成功":"删除失敗";
}
@ApiOperation("修改學生")
@PostMapping("/update")
public String update(@RequestBody Student student){
return studentService.updateById(student)?"修改成功":"修改失敗";
}
@ApiOperation(value = "查詢學生")
@GetMapping("/list")
public List<Student> list(){
Wrapper<Student> wrapper = new EntityWrapper<>();
return studentService.selectList(wrapper);
}
}
複制
package com.seawaterbt.ssm.controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.seawaterbt.ssm.entity.Teacher;
import com.seawaterbt.ssm.service.TeacherService;
import com.seawaterbt.ssm.vo.TeacherVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api("對老師表CRUD")
@RestController
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@ApiOperation(value = "添加老師")
@PostMapping("/add")
public String add(@RequestBody TeacherVo teacher){
Teacher tea = new Teacher();
tea.setName(teacher.getName());
tea.setAge(teacher.getAge());
tea.setSubject(teacher.getSubject());
return teacherService.insert(tea)?"添加成功":"添加失敗";
}
@ApiOperation("删除老師")
@DeleteMapping("/delete/{id}")
public String delete(@ApiParam("老師的主鍵id")@PathVariable(value = "id") Integer id){
return teacherService.deleteById(id)?"删除成功":"删除失敗";
}
@ApiOperation("修改老師")
@PostMapping("/update")
public String update(@RequestBody Teacher teacher){
return teacherService.updateById(teacher)?"修改成功":"修改失敗";
}
@ApiOperation(value = "查詢老師")
@GetMapping("/list")
public List<Teacher> list(){
Wrapper<Teacher> wrapper = new EntityWrapper<>();
return teacherService.selectList(wrapper);
}
}
複制