Spring Boot 揭秘与实战(二) 数据存储篇

时间:2021-02-15 00:17:23

文章目录

  1. 1. 环境依赖
  2. 2. 数据源3. 脚本初始化
    1. 2.1. 方案一 使用 Spring Boot 默认配置
    2. 2.2. 方案二 手动创建
  3. 4. MyBatis整合5. 总结
    1. 4.1. 方案一 通过注解的方式
      1. 4.1.1. 实体对象
      2. 4.1.2. DAO相关
      3. 4.1.3. Service相关
      4. 4.1.4. Controller相关
    2. 4.2. 方案二 通过配置文件的方式
      1. 4.2.1. 实体对象
      2. 4.2.2. 配置相关
      3. 4.2.3. DAO相关
      4. 4.2.4. Service相关
      5. 4.2.5. Controller相关
  4. 6. 源代码

本文讲解Spring Boot基础下,如何整合MyBatis框架,编写数据访问。

环境依赖

修改 POM 文件,添加mybatis-spring-boot-starter依赖。值得注意的是,可以不添加spring-boot-starter-jdbc。因为,mybatis-spring-boot-starter依赖中存在spring-boot-starter-jdbc。

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>1.1.1</version>
  5. </dependency>

添加mysql依赖。

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>5.1.35</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.0.14</version>
  10. </dependency>

数据源

方案一 使用 Spring Boot 默认配置

在 src/main/resources/application.properties 中配置数据源信息。

  1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
  3. spring.datasource.username=root
  4. spring.datasource.password=root

方案二 手动创建

在 src/main/resources/config/source.properties 中配置数据源信息。

  1. # mysql
  2. source.driverClassName = com.mysql.jdbc.Driver
  3. source.url = jdbc:mysql://localhost:3306/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
  4. source.username = root
  5. source.password = root

通过 Java Config 创建 dataSource 和jdbcTemplate 。

  1. @Configuration
  2. @EnableTransactionManagement
  3. @PropertySource(value = {"classpath:config/source.properties"})
  4. public class BeanConfig {
  5.  
  6. @Autowired
  7. private Environment env;
  8.  
  9. @Bean(destroyMethod = "close")
  10. public DataSource dataSource() {
  11. DruidDataSource dataSource = new DruidDataSource();
  12. dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
  13. dataSource.setUrl(env.getProperty("source.url").trim());
  14. dataSource.setUsername(env.getProperty("source.username").trim());
  15. dataSource.setPassword(env.getProperty("source.password").trim());
  16. return dataSource;
  17. }
  18.  
  19. @Bean
  20. public JdbcTemplate jdbcTemplate() {
  21. JdbcTemplate jdbcTemplate = new JdbcTemplate();
  22. jdbcTemplate.setDataSource(dataSource());
  23. return jdbcTemplate;
  24. }
  25. }

脚本初始化

先初始化需要用到的SQL脚本。

  1. CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
  2.  
  3. USE `springboot_db`;
  4.  
  5. DROP TABLE IF EXISTS `t_author`;
  6.  
  7. CREATE TABLE `t_author` (
  8. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  9. `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  10. `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  11. PRIMARY KEY (`id`)
  12. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

MyBatis整合

方案一 通过注解的方式

实体对象

  1. public class Author {
  2. private Long id;
  3. @JSONField(name="real_name")
  4. private String realName;
  5. @JSONField(name="nick_name")
  6. private String nickName;
  7.  
  8. // SET和GET方法
  9. }

DAO相关

  1. @Mapper
  2. public interface AuthorMapper {
  3.  
  4. @Insert("insert into t_author(real_name, nick_name) values(#{real_name}, #{nick_name})")
  5. int add(@Param("realName") String realName, @Param("nickName") String nickName);
  6.  
  7. @Update("update t_author set real_name = #{real_name}, nick_name = #{nick_name} where id = #{id}")
  8. int update(@Param("real_name") String realName, @Param("nick_name") String nickName, @Param("id") Long id);
  9.  
  10. @Delete("delete from t_author where id = #{id}")
  11. int delete(Long id);
  12.  
  13. @Select("select id, real_name as realName, nick_name as nickName from t_author where id = #{id}")
  14. Author findAuthor(@Param("id") Long id);
  15.  
  16. @Select("select id, real_name as realName, nick_name as nickName from t_author")
  17. List<Author> findAuthorList();
  18. }

Service相关

  1. @Service
  2. public class AuthorService {
  3. @Autowired
  4. private AuthorMapper authorMapper;
  5.  
  6. public int add(String realName, String nickName) {
  7. return this.authorMapper.add(realName, nickName);
  8. }
  9. public int update(String realName, String nickName, Long id) {
  10. return this.authorMapper.update(realName, nickName, id);
  11. }
  12. public int delete(Long id) {
  13. return this.authorMapper.delete(id);
  14. }
  15. public Author findAuthor(Long id) {
  16. return this.authorMapper.findAuthor(id);
  17. }
  18. public List<Author> findAuthorList() {
  19. return this.authorMapper.findAuthorList();
  20. }
  21. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController("mybatis.authorController")
  2. @RequestMapping(value="/data/mybatis/author")
  3. @MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
  4. public class AuthorController {
  5.  
  6. @Autowired
  7. private AuthorService authorService;
  8. /**
  9. * 查询用户列表
  10. */
  11. @RequestMapping(method = RequestMethod.GET)
  12. public Map<String,Object> getAuthorList(HttpServletRequest request) {
  13. List<Author> authorList = this.authorService.findAuthorList();
  14. Map<String,Object> param = new HashMap<String,Object>();
  15. param.put("total", authorList.size());
  16. param.put("rows", authorList);
  17. return param;
  18. }
  19. /**
  20. * 查询用户信息
  21. */
  22. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  23. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  24. Author author = this.authorService.findAuthor(userId);
  25. if(author == null){
  26. throw new RuntimeException("查询错误");
  27. }
  28. return author;
  29. }
  30.  
  31. /**
  32. * 新增方法
  33. */
  34. @RequestMapping(method = RequestMethod.POST)
  35. public void add(@RequestBody JSONObject jsonObject) {
  36. String userId = jsonObject.getString("user_id");
  37. String realName = jsonObject.getString("real_name");
  38. String nickName = jsonObject.getString("nick_name");
  39.  
  40. try{
  41. this.authorService.add(realName, nickName);
  42. }catch(Exception e){
  43. e.printStackTrace();
  44. throw new RuntimeException("新增错误");
  45. }
  46. }
  47. /**
  48. * 更新方法
  49. */
  50. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
  51. public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
  52. Author author = this.authorService.findAuthor(userId);
  53. String realName = jsonObject.getString("real_name");
  54. String nickName = jsonObject.getString("nick_name");
  55.  
  56. try{
  57. this.authorService.update(realName, nickName, author.getId());
  58. }catch(Exception e){
  59. e.printStackTrace();
  60. throw new RuntimeException("更新错误");
  61. }
  62. }
  63. /**
  64. * 删除方法
  65. */
  66. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
  67. public void delete(@PathVariable Long userId) {
  68. try{
  69. this.authorService.delete(userId);
  70. }catch(Exception e){
  71. throw new RuntimeException("删除错误");
  72. }
  73. }
  74. }

方案二 通过配置文件的方式

实体对象

  1. public class Author {
  2. private Long id;
  3. @JSONField(name="real_name")
  4. private String realName;
  5. @JSONField(name="nick_name")
  6. private String nickName;
  7.  
  8. // SET和GET方法
  9. }

配置相关

在 src/main/resources/mybatis/AuthorMapper.xml 中配置数据源信息。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.lianggzone.springboot.action.data.mybatis.dao.AuthorMapper2">
  5.  
  6. <!-- type为实体类Student,包名已经配置,可以直接写类名 -->
  7. <resultMap id="authorMap" type="Author">
  8. <id property="id" column="id" />
  9. <result property="realName" column="real_name" />
  10. <result property="nickName" column="nick_name" />
  11. </resultMap>
  12.  
  13. <select id="findAuthor" resultMap="authorMap" resultType="Author">
  14. select id, real_name, nick_name from t_author where id = #{id}
  15. </select>
  16. </mapper>

在 src/main/resources/application.properties 中配置数据源信息。

  1. mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml
  2. mybatis.type-aliases-package=com.lianggzone.springboot.action.data.mybatis.entity

DAO相关

  1. public interface AuthorMapper2 {
  2. Author findAuthor(@Param("id") Long id);
  3. }

Service相关

  1. @Service
  2. public class AuthorService2 {
  3. @Autowired
  4. private AuthorMapper2 authorMapper;
  5.  
  6. public Author findAuthor(Long id) {
  7. return this.authorMapper.findAuthor(id);
  8. }
  9. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController("mybatis.authorController2")
  2. @RequestMapping(value="/data/mybatis/author2")
  3. @MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
  4. public class AuthorController2 {
  5. @Autowired
  6. private AuthorService2 authorService;
  7. /**
  8. * 查询用户信息
  9. */
  10. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  11. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  12. Author author = this.authorService.findAuthor(userId);
  13. if(author == null){
  14. throw new RuntimeException("查询错误");
  15. }
  16. return author;
  17. }
  18. }

总结

上面这个简单的案例,让我们看到了 Spring Boot 整合 MyBatis 框架的大概流程。那么,复杂的场景,大家可以参考使用一些比较成熟的插件,例如com.github.pagehelper、mybatis-generator-maven-plugin等。

源代码

相关示例完整代码: springboot-action

(完)

 


Spring Boot 揭秘与实战(二) 数据存储篇