springboot

SpringBoot整合Mybatis注解版

2020-03-09  本文已影响0人  CodePandaes

SpringBoot+Mybatis+druid整合详细过程,这里使用的是druid连接池(亦可以使用hikari连接池,参考SpringBoot整合hikari),具体参数配置请参考我的上一篇博客SpringBoot整合druid
欢迎大家访问 我的Hexo博客

项目准备

首先新建一个SpringBoot的web项目,选择Spring Initializr(用来初始化一个Spring boot 的项目)

然后填写项目坐标,自行修改

最后选择要添加的组件web,Mybatis,mysql新建成功


配置

打开pom.xml文件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
       <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
         <!--添加druid依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <!--导入log4j,因为driud添加的拓展插件为log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

打开配置文件application.yml添加具体属性

========================
#数据源基本配置
spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver# 时区配置错误就添加 serverTimezone = UTC
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
    #druid增加的配置
    type: com.alibaba.druid.pool.DruidDataSource
=========================以下配置酌情处理===========
    # 初始化连接池个数
    initialSize: 5
    # 最小连接池个数
    minIdle: 5
    # 最大连接池个数
    max-active: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测
    timeBetweenEvictionRunsMillis: 60000
    # 最小生存的时间
    minEvictableIdleTimeMillis: 300000
    # 用来检测连接是否有效的sql,要求是一个查询语句。
    # 如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用
    validationQuery: SELECT 1 FROM DUAL
    # 建议配置为true,不影响性能,并且保证安全性。
    # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
    testWhileIdle: true
    # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
    testOnBorrow: false
    # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
    testOnReturn: false
    # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 通过别名的方式配置扩展插件,多个英文逗号分隔,常用的插件有:
    # 监控统计用的filter:stat
    # 日志用的filter:log4j
    # 防御sql注入的filter:wall
    filters: stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    useGlobalDataSourceStat: true

添加配置类MyBatisConfig开启驼峰命名

public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true); //开启驼峰
            }
        };
    }
}

添加实体类Department

public class Department {
    private Integer id;
    private String departmentName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
}

打开数据库管理工具新建名为mybatis的数据库,执行Department类对应sql脚本

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

添加接口DepartmentMapper,使用注解增删改查,这里只演示insert和select

public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    Department getDeptById(Integer id);

    //使用自动生成的主键,并告诉是那个属性是封装主键的
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(department_name) values(#{departmentName})")
    int insertDept(Department department);
}

在启动类上添加@MapperScan扫描mapper包

@MapperScan(value = "com.springboot.mapper")
@SpringBootApplication
public class SpringBootDataMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDataMybatisApplication.class, args);
    }

}

添加DeptController类

@RestController
public class DeptController {

    @Autowired
    private DepartmentMapper departmentMapper;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/insert")
    public Department insertDept(Department department) {
        departmentMapper.insertDept(department);
        return department;
    }
}

启动项目,在浏览器输入localhost:8080/insert?departmentName=huawei,新增数据成功

然后再输入localhost:8080/dept/1,获取departmentName=huawei的数据

上一篇 下一篇

猜你喜欢

热点阅读