2019-11-07 5 分钟 读完 (大约 753 个字) 0 次访问
SpringBoot-Mybatis Spring Boot-Mybatis
1. ORM框架选型
对比项
SPRING DATA JPA
MYBATIS
单表操作方式
只需继承,代码量较少,非常方便。而且支持方法名用关键字生成SQL
可以使用代码生成工具,也很方便,但相对JPA单表弱很多。JPA单表操作非常简单
多表关联查询
友好,动态SQL使用不够方便,而且SQL和代码耦合到一起
非常友好,可以有非常直观的动态SQL
自定义SQL
SQL写在注解里面,写动态SQL有些费劲
SQL可以写在XML里,独立管理,动态SQL语法也容易书写理解
学习成本
略高
较低,会写SQL就可以
JPA是规范,Hibernate是实现
Spring Data JPA 对开发人员更加友好,单表操作非常方便,多表关联也不麻烦
mybatis各方面都很优秀,使用范围更广
大型项目建议mybatis
2. 整合MyBatis操作数据库
1 2 3 4 5 6 7 8 9 10 <dependency > <groupId > org.mybatis.spring.boot</groupId > <artifactId > mybatis-spring-boot-starter</artifactId > <version > 2.1.1</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <scope > runtime</scope > </dependency >
1 2 3 4 5 6 7 8 9 10 11 12 13 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration > <settings > <setting name ="useGeneratedKeys" value ="true" /> <setting name ="useColumnLabel" value ="true" /> <setting name ="mapUnderscoreToCamelCase" value ="true" /> </settings > </configuration >
同样的内容也可以写在Spring Boot配置文件application.yml中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 spring: datasource: username: root password: Thwf1858 url: jdbc:mysql://localhost:3306/mybatis driver-class-name: com.mysql.jdbc.Driver logging: level: com.haven.mybatis.mapper: debug mybatis: configuration: map-underscore-to-camel-case: true use-generated-keys: true use-column-label: true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package com.hehe.mapper;@Mapper public interface UserMapper { @Select ("select * from t_user" ) List<User> list () ; @SelectProvider (type = UserSqlProvider.class, method = "listByUsername" ) List<User> listByUsername (String username) ; @Results ({ @Result (property = "userId" , column = "USER_ID" ), @Result (property = "username" , column = "USERNAME" ), @Result (property = "password" , column = "PASSWORD" ), @Result (property = "mobileNum" , column = "PHONE_NUM" ) }) @Select ("select * from t_user" ) List<User> listSample () ; @Select ("select * from t_user where username like #{username} and password like #{password}" ) User get (@Param("username" ) String username, @Param ("password" ) String password) ; @SelectProvider (type = UserSqlProvider.class, method = "getBadUser" ) User getBadUser (@Param("username" ) String username, @Param ("password" ) String password) ; }