Spring Boot 整合 MyBatis

1. 环境准备

  • 第一步:导入数据库表
  • 第二步:加入MyBatis的启动器依赖 ``` org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.0 mysql mysql-connector-java com.mchange c3p0 0.9.5.2
  1. -
  2. **第三步:加入配置文件**
  3. - 参考spring-boot-autoconfigure-1.5.6.RELEASE.jarjdbc包中属性文件类**DataSourceProperties**

@ConfigurationProperties(prefix = “spring.datasource”) public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {

  1. private ClassLoader classLoader;
  2. /**
  3. * Name of the datasource. Default to "testdb" when using an embedded database.
  4. */
  5. private String name;
  6. /**
  7. * Whether to generate a random datasource name.
  8. */
  9. private boolean generateUniqueName;
  10. /**
  11. * Fully qualified name of the connection pool implementation to use. By default, it
  12. * is auto-detected from the classpath.
  13. */
  14. private Class<? extends DataSource> type;
  15. /**
  16. * Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
  17. */
  18. private String driverClassName;
  19. /**
  20. * JDBC URL of the database.
  21. */
  22. private String url;
  23. /**
  24. * Login username of the database.
  25. */
  26. private String username;
  27. /**
  28. * Login password of the database.
  29. */
  30. private String password;

…… }

  1. - 参考mybatis-spring-boot-autoconfigure-1.3.0.jar中属性文件类**MybatisProperties**

@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX) public class MybatisProperties {

public static final String MYBATIS_PREFIX = “mybatis”;

/**

  • Location of MyBatis xml config file. */ private String configLocation;

    /**

  • Locations of MyBatis mapper files. */ private String[] mapperLocations;

    /**

  • Packages to search type aliases. (Package delimiters are “,; \t\n”) */ private String typeAliasesPackage;

    /**

  • Packages to search for type handlers. (Package delimiters are “,; \t\n”) */ private String typeHandlersPackage;

    /**

  • Indicates whether perform presence check of the MyBatis xml config file. */ private boolean checkConfigLocation = false;

    /**

  • Execution mode for {@link org.mybatis.spring.SqlSessionTemplate}. */ private ExecutorType executorType;

    /**

  • Externalized properties for MyBatis configuration. */ private Properties configurationProperties;

    /**

  • A Configuration object for customize default settings. If {@link #configLocation}
  • is specified, this property is not used. */ @NestedConfigurationProperty private Configuration configuration; …… }
  1. src/main/resources下添加application.properties(或application.yml)配置文件,内容如下:

配置数据源

spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db spring.datasource.username=root spring.datasource.password=123456 spring.datasource.type=com.mchange.v2.c3p0.ComboPooledDataSource

配置MyBatis3

配置类型别名扫描基础包

mybatis.typeAliasesPackage=com.moon.springboot.domain

配置SQL语句映射文件

mybatis.mapperLocations=classpath:mappers/*/Mapper.xml

配置核心配置文件

mybatis.configLocation=classpath:mybatis-config.xml

  1. 使用yml配置文件

mybatis: mapper-locations: classpath:mappers/*/.xml type-aliases-package: com.moon.demo.pojo

  1. # 开启驼峰映射
  2. configuration:
  3. map-underscore-to-camel-case: true
  1. **注:传统的ssm框架中,mybatis的总配置文件是mybatis-config.xml,但spring boot推荐少用配置文件,所以,可以将mybatis-config.xml的相关配置写在application.properties(或 application.yml)中**
  2. ## 2. application文件相关配置
  3. - 任何其他Spring Boot应用程序一样,MyBatis-Spring-Boot-Application配置参数存储在application.properties(或application.yml)中。
  4. - MyBatis使用前缀mybatis作为其属性
  5. ### 2.1. 可用的属性
  6. |
  7. **属性**
  8. | **描述**
  9. |
  10. | --- | --- |
  11. |
  12. config-location
  13. | MyBatis xml配置文件的位置
  14. |
  15. |
  16. check-config-location
  17. | 指示是否执行MyBatis xml配置文件的状态检查
  18. |
  19. |
  20. mapper-locations
  21. | Mapper xml映射文件的位置
  22. |
  23. |
  24. type-aliases-package
  25. | 用于搜索类型别名的包。 (包分隔符是“,; \\ t \\ n”)
  26. |
  27. |
  28. type-handlers-package
  29. | 用于搜索类型处理程序的包。 (包分隔符是“,; \\ t \\ n”)
  30. |
  31. |
  32. executor-type
  33. | 执行者类型:SIMPLEREUSEBATCH
  34. |
  35. |
  36. configuration-properties
  37. | MyBatis配置的外部化属性。指定的属性可以用作MyBatis配置文件和Mapper文件的占位符
  38. |
  39. |
  40. configuration
  41. | MyBatis相关配置bean。关于可用属性,与mybatis-config.xml配置文件的settings配置属性一致。**注意此属性不能config-location同时使用**
  42. |
  43. ### 2.2. 配置案例

application.properties

mybatis.type-aliases-package=com.example.domain.model mybatis.type-handlers-package=com.example.typehandler mybatis.configuration.map-underscore-to-camel-case=true mybatis.configuration.default-fetch-size=100 mybatis.configuration.default-statement-timeout=30 …

  1. ```
  2. # application.yml
  3. mybatis:
  4. type-aliases-package: com.example.domain.model
  5. type-handlers-package: com.example.typehandler
  6. configuration:
  7. map-underscore-to-camel-case: true
  8. default-fetch-size: 100
  9. default-statement-timeout: 30
  10. ...

3. 整合开发Demo

  • 使用Spring Boot + Spring MVC + MyBatis实现查询所有公告
  • 使用Spring Boot + Spring MVC + MyBatis + EasyUI 实现公告分页查询
  • 第一步:创建domain
  1. public class Notice implements Serializable {
  2. private static final long serialVersionUID = 5679176319867604937L;
  3. private Long id;
  4. private String title;
  5. private String content;
  6. /** setter and getter method */
  7. public Long getId() {
  8. return id;
  9. }
  10. public void setId(Long id) {
  11. this.id = id;
  12. }
  13. public String getTitle() {
  14. return title;
  15. }
  16. public void setTitle(String title) {
  17. this.title = title;
  18. }
  19. public String getContent() {
  20. return content;
  21. }
  22. public void setContent(String content) {
  23. this.content = content;
  24. }
  25. }
  • 第二步:编写NoticeMapper接口。和之前的方式一样,只是多了@Mapper个注解。@Mapper:声明Mapper接口
  • 注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
  1. @Mapper
  2. public interface NoticeMapper {
  3. /** 查询所有公告 */
  4. @Select("select * from notice")
  5. public List<Notice> findAll();
  6. /** 统计查询 */
  7. public Long count();
  8. /** 分页查询公告 */
  9. public List<Notice> findByPage(@Param("page")Integer page, @Param("rows")Integer rows);
  10. }
  • 第三步:编写src/main/resources/mappers/NoticeMapper.xml文件 ``` <?xml version=”1.0” encoding=”UTF-8” ?> <!DOCTYPE mapper

    1. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    2. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  1. - **第四步:编写Service与实现类**

public interface NoticeService { / 查询所有的公告 */ public List findAll(); / 分页查询公告 */ public Map findByPage(Integer page, Integer rows); }

@Service @Transactional public class NoticeServiceImpl implements NoticeService { @Autowired private NoticeMapper noticeMapper; / 查询所有的公告 */ public List findAll(){ return noticeMapper.findAll(); } / 分页查询公告 / public Map findByPage(Integer page, Integer rows){ /** 创建Map集合封装响应数据 / Map data = new HashMap<>(); / 统计查询 */ long count = noticeMapper.count(); data.put(“total”, count); / 分页查询 */ List notices = noticeMapper.findByPage(page, rows); data.put(“rows”, notices); return data; } }

  1. - **第五步:编写Controller**

@Controller public class NoticeController { @Autowired private NoticeService noticeService; / 查询全部公告 */ @GetMapping(“/findAll”) @ResponseBody public List findAll(){ return noticeService.findAll(); } / 跳转分页查询公告页面 / @GetMapping(“/show”) public String show(){ return “/html/notice.html”; } /** 分页查询公告 / @PostMapping(“/findByPage”) @ResponseBody public Map findByPage(@RequestParam(value=”page”, defaultValue=”1”, required=false)Integer page, @RequestParam(value=”rows”, defaultValue=”15”, required=false)Integer rows){ return noticeService.findByPage((page - 1) * rows, rows); } }

```

  • 第六步:加入静态资源

src/main/resources/public/html/notice.html
src/main/resources/static/js
src/main/resources/static/css
src/main/resources/static/images