笔记
2、SpringBoot2.x整合Mybatis3.x注解实战 简介:SpringBoot2.x整合Mybatis3.x注解配置实战 1、使用starter, maven仓库地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter 2、加入依赖(可以用 http://start.spring.io/ 下载) <!-- 引入starter--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> <scope>runtime</scope> </dependency> <!-- MySQL的JDBC驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 引入第三方数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> 3、加入配置文件 #mybatis.type-aliases-package=net.xdclass.base_project.domain #可以自动识别 #spring.datasource.driver-class-name =com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8 spring.datasource.username =root spring.datasource.password =password #如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource) spring.datasource.type =com.alibaba.druid.pool.DruidDataSource 加载配置,注入到sqlSessionFactory等都是springBoot帮我们完成 4、启动类增加mapper扫描 @MapperScan("net.xdclass.base_project.mapper") 技巧:保存对象,获取数据库自增id @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") 4、开发mapper 参考语法 http://www.mybatis.org/mybatis-3/zh/java-api.html 5、sql脚本 CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(128) DEFAULT NULL COMMENT '名称', `phone` varchar(16) DEFAULT NULL COMMENT '用户手机号', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `age` int(4) DEFAULT NULL COMMENT '年龄', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8; 相关资料: http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples 整合问题集合: https://my.oschina.net/hxflar1314520/blog/1800035 https://blog.csdn.net/tingxuetage/article/details/80179772开始
这里用注解的方式,因为比较简单,
mapper:数据库接口,访问数据库那一层的接口 service:业务逻辑 util:工具类 user类 自动生成项目的形式 一般不用最新版本 可能会有bug 数据源一般用阿里巴巴的druid数据源。把下面三个依赖都加进去 热部署也加进来了 加入配置文件 默认的数据库连接池。如果把Druid这个阿里巴巴的注释掉。就会用默认的了 这里连接的是movie数据库下的user表启动类加上扫描对应的包
扫描的是mapper这个包下 mapper相当于dao层
复制mapper里面的类的完整包名 mapper的开发可以参考官方文档 这里的主键是自增的 拿到自增的id service就是一个接口,里面定义方法 service的实现类。getId就是增加后获取到的主键id Service的实现类记得用@Service的注解controller
测试
启动程序
code返回的是0。data是45,data是主键的id 再保存一个就是46 数据库内保存了46的数据相关的资料
相关资料:
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples 整合问题集合: https://my.oschina.net/hxflar1314520/blog/1800035 https://blog.csdn.net/tingxuetage/article/details/80179772