Spring Boot + MyBatis + MySQL 整合

作者: FlySheep_ly | 来源:发表于2017-03-25 09:16 被阅读13675次

    一、前言

    昨天在弄 Spring Boot 与 MyBatis 的整合,首先在网上查看了很多人写的文章,参照前人的经验就开始整了,结果整了一天都是 bug,后来自己到官网上查看官方文档后才得以顺手解决,这也让自己以后要吸取教训,最好先看官方文档,然后再实践。结合自己查看的网上关于 Spring Boot 与 MyBatis 整合的文章,有得写的相当复杂,有的是按照文中描述进行实践后发现不行,所以自己再对其进行总结。我使用的是采用 全注解的方式来实现 MyBatis,这也正好符合 Spring Boot 的思想:使用注解,少用配置文件。最后也加上了个使用 XML 配置的代码。

    二、整合步骤

    1. 在 pom.xml 的文件中添加以下依赖:

            <!-- 添加 MyBatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.2.0</version>
            </dependency>
    
            <!-- 添加 MySQL -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.41</version>
            </dependency>
    

    这里我们看到在项目中使用的是 MyBatis 官方提供的 starter,mybatis-spring-boot-starter 的 Github 源码地址为: https://github.com/mybatis/spring-boot-starter ,mybatis-spring-boot-stater的官方文档地址:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ ,MyBatis 官方中文文档:http://www.mybatis.org/mybatis-3/zh/java-api.html

    2. 在 application.properties 文件中添加数据库的配置

    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
    spring.datasource.username=root
    spring.datasource.password=123
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    

    3. 新建 DAO 接口,里面编写增、删、改、查方法

    @Mapper
    public interface PersonMapper {
    
        /**
         * 添加操作,返回新增元素的 ID
         *
         * @param personDO
         */
        @Insert("insert into person(name,age) values(#{name},#{age})")
        @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
        void insert(PersonDO personDO);
    
        /**
         * 更新操作
         *
         * @param personDO
         * @return 受影响的行数
         */
        @Update("update person set name=#{name},age=#{age} where id=#{id}")
        Long update(PersonDO personDO);
    
        /**
         * 删除操作
         *
         * @param id
         * @return 受影响的行数
         */
        @Delete("delete from person where id=#{id}")
        Long delete(@Param("id") Long id);
    
        /**
         * 查询所有
         *
         * @return
         */
        @Select("select id,name,age from person")
        List<PersonDO> selectAll();
    
        /**
         * 根据主键查询单个
         *
         * @param id
         * @return
         */
        @Select("select id,name,age from person where id=#{id}")
        PersonDO selectById(@Param("id") Long id);
    }
    

    这里全部使用的是注解的方式,关于 MyBatis 的所有注解,可以参考 MyBatis 的中文文档。

    4. 编写 Controller

    @EnableTransactionManagement  // 需要事务的时候加上
    @RestController
    public class PersonController {
    
        @Autowired
        private PersonMapper personMapper;
    
        @RequestMapping("/save")
        public Integer save() {
            PersonDO personDO = new PersonDO();
            personDO.setName("张三");
            personDO.setAge(18);
            personMapper.insert(personDO);
            return personDO.getId();
        }
    
        @RequestMapping("/update")
        public Long update() {
            PersonDO personDO = new PersonDO();
            personDO.setId(2);
            personDO.setName("旺旺");
            personDO.setAge(12);
            return personMapper.update(personDO);
        }
    
        @RequestMapping("/delete")
        public Long delete() {
            return personMapper.delete(11L);
        }
    
        @RequestMapping("/selectById")
        public PersonDO selectById() {
            return personMapper.selectById(2L);
        }
    
        @RequestMapping("/selectAll")
        public List<PersonDO> selectAll() {
            return personMapper.selectAll();
        }
    
        @RequestMapping("/transaction")
        @Transactional  // 需要事务的时候加上
        public Boolean transaction() {
            delete();
    
            int i = 3 / 0;
    
            save();
    
            return true;
        }
    
    }
    

    至此,运行就可以测试了,是不是很简单。关于注解的使用可以参考这篇文章:http://blog.csdn.net/luanlouis/article/details/35780175 ,最后奉上代码地址:https://github.com/435242634/Spring-Boot-Demo/tree/feature/3-spring-boot-mybatis

    三、使用 XML 配置

    上面介绍的是全使用注解的方式配置,但是很多时候我们还是使用 XML 配置 SQL 文件,这里不再多介绍,直接加上我写的一个使用 XML 配置的代码地址:https://github.com/435242634/Spring-Boot-Demo/tree/feature/4-spring-boot-mybatis-xml

    相关文章

      网友评论

      • 贰肆陆玐:初学者感觉还是有些细节不明白啊
      • 4b18eaaad795:Description:
        Field personMapper in com.example.controller.PersonController required a bean of type 'com.example.dao.PersonMapper' that could not be found.
        Action:
        Consider defining a bean of type 'com.example.dao.PersonMapper' in your configuration.

        找不到mapper啊?
        兄弟什么问题啊?
        谭小琼:实在不行在application类里面加一个MapperScan注解。参考http://www.cnblogs.com/ityouknow/p/6037431.html
        FlySheep_ly:@RootZ @mapper 你加了吗
      • 1emontree:entity层中的代码是直接写的还是导入的啊
        FlySheep_ly:我是自己直接写的
      • 003be78a6f72:我基本是这么写的,就报错了,错误是Error creating bean with name 'dataSource' defined in class path resource ,知道是怎么回事吗?
      • 70342eb43d60:不需要配置mybatis吗?我在yml文件里配置
        mybatis:
        type-aliases-package: testspringboot1.entity
        mapper-locations: classpath:mapper/*.xml
        结果跑不起来阿
        FlySheep_ly:应该是你数据库连接没配置好,需要帮助的话可以加我 QQ:435242634
        70342eb43d60:@FlySheep_ly
        JSON:
        {
        "timestamp": 1491219100964,
        "status": 500,
        "error": "Internal Server Error",
        "exception": "org.mybatis.spring.MyBatisSystemException",
        "message": "nested exception is org.apache.ibatis.exceptions.PersistenceException: \n### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure\n\nThe last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.\n### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure\n\nThe last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.",
        "path": "/test/deleteById/1"
        }

        控制台打印:
        2017-04-03 19:31:40.929 ERROR 18300 --- [nio-8080-exec-1] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.

        我用的gradle:依赖:
        compile('org.springframework.boot:spring-boot-starter-jdbc')
        compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.2.0')
        compile('org.springframework.boot:spring-boot-starter-web')
        compile('mysql:mysql-connector-java')
        compileOnly('org.projectlombok:lombok')
        testCompile('org.springframework.boot:spring-boot-starter-test')
        compile('c3p0:c3p0:0.9.1.2')

        应该是mybatis没有配置好 不过不应该阿
        FlySheep_ly:@jianandgui 有错误日志吗?贴出来看看
      • y0ngb1n:直接不要service层了吗:scream:
        FlySheep_ly:@ybin1212 我为了方便测试,就直接把service 层去了

      本文标题:Spring Boot + MyBatis + MySQL 整合

      本文链接:https://www.haomeiwen.com/subject/hpnqottx.html