SpringBoot与Mybatis合并
一、创建SpringBoot项目,引入相关依赖包:
4.0.0 com.cn spring-boot-mybatis 1.0-SNAPSHOT UTF-8 1.8 org.springframework.boot spring-boot-dependencies 2.0.1.RELEASE <!-- mysql 数据库驱动. --> org.springframework.boot spring-boot-starter-web <!-- spring-boot mybatis依赖 --> mysql mysql-connector-java org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 <!-- 打包插件 --> org.springframework.boot spring-boot-maven-plugin <!--Mybatis-generator插件,用于自动生成Mapper和POJO--> org.mybatis.generator mybatis-generator-maven-plugin 1.3.2 <!--配置文件的位置--> src/main/resources/mybatis/mybatis-generator.xml true true Generate MyBatis Artifacts generate mysql mysql-connector-java 5.1.46 org.mybatis.generator mybatis-generator-core 1.3.2
项目目录:

二、创建mybatis-generator.xml生成器配置文件(在lib目录中放入相应的mysql连接器mysql-connector-java-5.1.46.jar):
generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><!-- 数据库驱动 --> <!--数据库链接URL,用户名、密码 --> <!-- 是否去除自动生成的注释 true:是 ; false:否 --> <!--数据库链接URL,用户名、密码 --> <!-- --> <!-- 生成模型的包名和位置 --> <!-- 生成映射文件的包名和位置 --> <!-- 生成DAO的包名和位置 --> <!-- 要生成哪些表 -->
由于上一步已添加相关的插件依赖,只需在maven管理的plugins中启动mybatis-generator:

三、创建application.properties、controller、service:
spring.datasource.url=jdbc:mysql://192.168.1.121:3306/testspring.datasource.username=root spring.datasource.password=admincss spring.datasource.driver-class-name=com.mysql.jdbc.Driver #必须配置,否则会找不到映射的xml mybatis.mapper-locations=classpath:mybatis/mapper/*.xml



四、在生成的Mapper类中,添加@Mapper注解,目的在于将该Mapper添加进spring容器中或者可以在启动类中配置@MapperScan扫描范围:
package com.cn.mapper;import com.cn.entity.Student;import org.apache.ibatis.annotations.Mapper;
@Mapperpublic interface StudentMapper { int deleteByPrimaryKey(Integer id); int insert(Student record); int insertSelective(Student record);
Student selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record);
}
五、启动,测试:

代码实例:https://gitee.com/lfalex/spring-boot-example/tree/dev/spring-boot-mybatis
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2079/viewspace-2802215/ ,如需转载,请注明出处,否则将追究法律责任。