当前位置:   article > 正文

SpringBoot 2.0集成MySQL+mybatis+Druid配置_springboot如何配置mybatis,使用mysql和druid框架

springboot如何配置mybatis,使用mysql和druid框架

本文采用的springboot版本为2.1.4,mybatis版本为1.3.2,Druid版本为1.1.10

springboot项目骨架生成不在赘述,idea可以用spring initializr生成,或者直接到spring官网https://start.spring.io生成,下载之后导入到idea中。

1.引入jar包,pom文件如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.4.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>springbucks</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springbucks</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <!--打开监控-->
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-actuator</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-jdbc</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-web</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.mybatis.spring.boot</groupId>
  35. <artifactId>mybatis-spring-boot-starter</artifactId>
  36. <version>1.3.2</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>mysql</groupId>
  40. <artifactId>mysql-connector-java</artifactId>
  41. <scope>runtime</scope>
  42. </dependency>
  43. <!-- druid数据源 -->
  44. <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
  45. <dependency>
  46. <groupId>com.alibaba</groupId>
  47. <artifactId>druid-spring-boot-starter</artifactId>
  48. <version>1.1.10</version>
  49. </dependency>
  50. <dependency>
  51. <groupId>org.projectlombok</groupId>
  52. <artifactId>lombok</artifactId>
  53. <optional>true</optional>
  54. </dependency>
  55. <dependency>
  56. <groupId>org.springframework.boot</groupId>
  57. <artifactId>spring-boot-starter-test</artifactId>
  58. <scope>test</scope>
  59. </dependency>
  60. </dependencies>
  61. <build>
  62. <plugins>
  63. <plugin>
  64. <groupId>org.springframework.boot</groupId>
  65. <artifactId>spring-boot-maven-plugin</artifactId>
  66. </plugin>
  67. </plugins>
  68. </build>
  69. </project>

pom中引入了actuator监控、druid、mybatis、lombok、mysql等依赖

2.application.yml配置如下:

  1. server:
  2. port: 8088
  3. spring:
  4. application:
  5. name: spring-bucks
  6. datasource:
  7. druid:
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. url: jdbc:mysql://localhost/demo?characterEncoding=UTF-8&useSSL=false
  10. username: developer
  11. password: developer12321
  12. filters: stat,wall
  13. initial-size: 3
  14. min-idle: 1
  15. max-active: 20
  16. test-on-borrow: false
  17. test-on-return: false
  18. test-while-idle: true
  19. validation-query: select 'x'
  20. max-wait: 6000
  21. pool-prepared-statements: true
  22. time-between-eviction-runs-millis: 60000
  23. min-evictable-idle-time-millis: 60000
  24. web-stat-filter:
  25. enabled: true
  26. url-pattern: "/*"
  27. stat-view-servlet:
  28. enabled: true
  29. url-pattern: /druid/*
  30. reset-enable: false
  31. login-username: admin
  32. login-password: admin
  33. mybatis:
  34. configuration:
  35. map-underscore-to-camel-case: true
  36. type-handlers-package: com.example.springbucks.handler
  37. type-aliases-package: com.example.springbucks.model
  38. mapper-locations: classpath:mappers/*.xml
  39. logging:
  40. level:
  41. com:
  42. example:
  43. springbucks:
  44. dao: debug
  45. management:
  46. endpoints:
  47. web:
  48. exposure:
  49. include: "*"

druid各项配置建议参考durid官方文档https://github.com/alibaba/druid/wiki

这里重点说几个mybatis的配置

map-underscore-to-camel-case: true

这项配置可以实现数据库表字段和类变量名的自动映射,例如列名create_time会自动映射到字段名createTime,省去写ResultMap的麻烦,这里建议大家开发时都能遵守一定的规范,可以提高效率

type-aliases-package: com.example.springbucks.model

大家知道在mapper文件中写ParameterType和ResultType时必须是全包名,很不便利,这个配置只需要写实体类的别名就行了,但是在实体类上要加入注解。如下,在mapper中,com.example.springbucks.model.Coffee可以直接用coffee代替

  1. package com.example.springbucks.model;
  2. import lombok.*;
  3. import lombok.experimental.Accessors;
  4. import org.apache.ibatis.type.Alias;
  5. import org.joda.money.Money;
  6. import org.springframework.data.mongodb.core.mapping.Document;
  7. import java.io.Serializable;
  8. /**
  9. * @author Gary
  10. * @className Coffee
  11. * @description TODO
  12. * @date 2019-04-13 19:06
  13. **/
  14. @Document
  15. @Data
  16. @ToString(callSuper = true)
  17. @EqualsAndHashCode(callSuper = false)
  18. @NoArgsConstructor
  19. @AllArgsConstructor
  20. @Accessors(chain = true)
  21. @Alias("coffee")
  22. public class Coffee extends BaseModel implements Serializable {
  23. private String name;
  24. private Money price;
  25. }
  1. <select id="search" parameterType="coffee" resultType="coffee">
  2. SELECT
  3. *
  4. FROM
  5. t_coffee t
  6. <where>
  7. <if test="name != null and name != ''">
  8. AND t.NAME LIKE LOWER( '%${name}%' )
  9. </if>
  10. <if test="price != null">
  11. AND t.price = #{price}
  12. </if>
  13. ORDER BY id
  14. </where>
  15. </select>

mapper-locations: classpath:mappers/*.xml

指定mapper文件的路径

3.启动类配置

@MapperScan("com.example.springbucks.dao")

启动类加入@MapperScan注解之后,spring会到相应的包下面扫描,不需要在每个dao接口里加@Mapper注解

4.dao

  1. package com.example.springbucks.dao;
  2. import com.example.springbucks.model.Coffee;
  3. import org.apache.ibatis.annotations.*;
  4. import org.apache.ibatis.session.RowBounds;
  5. import java.util.List;
  6. /**
  7. * TODO
  8. *
  9. * @author Gary
  10. *
  11. * @date 2019-04-13 19:24
  12. */
  13. public interface CoffeeDao {
  14. /**
  15. * @description: 新增coffee
  16. * @author Gary
  17. * @param coffee
  18. *
  19. * @return java.lang.Long
  20. * @date 2019-04-07 20:59
  21. */
  22. @Insert("insert into t_coffee (name, price, create_time, update_time) " +
  23. "values (#{name}, #{price}, now(), now())")
  24. @Options(useGeneratedKeys = true)
  25. Long save(Coffee coffee);
  26. /**
  27. * 根据id查询coffee
  28. * @description:
  29. * @author Gary
  30. * @param id
  31. *
  32. * @return com.example.mybatisdemo.model.Coffee
  33. * @date 2019-04-07 20:59
  34. */
  35. @Select("select * from t_coffee where id = #{id}")
  36. @Results({
  37. @Result(id = true, column = "id", property = "id")
  38. })
  39. Coffee findById(Long id);
  40. /**
  41. * 分页查询
  42. *
  43. * @description: TODO
  44. * @author Gary
  45. * @param rowBounds
  46. *
  47. * @return java.util.List<com.example.mybatisdemo.model.Coffee>
  48. * @date 2019-04-07 21:13
  49. */
  50. @Select("select * from t_coffee order by id")
  51. List<Coffee> findAllWithRowBounds(RowBounds rowBounds);
  52. List<Coffee> search(Coffee coffee);
  53. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.springbucks.dao.CoffeeDao">
  4. <select id="search" parameterType="coffee" resultType="coffee">
  5. SELECT
  6. *
  7. FROM
  8. t_coffee t
  9. <where>
  10. <if test="name != null and name != ''">
  11. AND t.NAME LIKE LOWER( '%${name}%' )
  12. </if>
  13. <if test="price != null">
  14. AND t.price = #{price}
  15. </if>
  16. ORDER BY id
  17. </where>
  18. </select>
  19. </mapper>

5.service

  1. package com.example.springbucks.service;
  2. import com.example.springbucks.model.Coffee;
  3. import org.apache.ibatis.annotations.Param;
  4. import java.util.List;
  5. /**
  6. * @author Gary
  7. * @className CoffeeService
  8. * @description TODO
  9. * @date 2019-04-13 19:16
  10. **/
  11. public interface CoffeeService {
  12. Long save(Coffee coffee);
  13. Coffee findById(Long id);
  14. List<Coffee> findAllByPage(@Param("pageNum") int pageNum,
  15. @Param("pageSize") int pageSize);
  16. List<Coffee> search(Coffee coffee);
  17. }
  1. package com.example.springbucks.service.impl;
  2. import com.example.springbucks.dao.CoffeeDao;
  3. import com.example.springbucks.model.Coffee;
  4. import com.example.springbucks.service.CoffeeService;
  5. import org.apache.ibatis.session.RowBounds;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import java.util.List;
  9. /**
  10. * @author Gary
  11. * @className CoffeeServiceImpl
  12. * @description TODO
  13. * @date 2019-04-13 19:25
  14. **/
  15. @Service("coffeeService")
  16. public class CoffeeServiceImpl implements CoffeeService {
  17. @Autowired
  18. private CoffeeDao coffeeDao;
  19. @Override
  20. public Long save(Coffee coffee) {
  21. return coffeeDao.save(coffee);
  22. }
  23. @Override
  24. public Coffee findById(Long id) {
  25. return coffeeDao.findById(id);
  26. }
  27. @Override
  28. public List<Coffee> findAllByPage(int pageNum, int pageSize) {
  29. RowBounds rowBounds = new RowBounds(pageNum, pageSize);
  30. return coffeeDao.findAllWithRowBounds(rowBounds);
  31. }
  32. @Override
  33. public List<Coffee> search(Coffee coffee) {
  34. return coffeeDao.search(coffee);
  35. }
  36. }

6.启动项目之后可到http://localhost:8088/druid/login.html页面查看druid的相关信息

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/46456
推荐阅读
相关标签
  

闽ICP备14008679号