You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 7.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. # spring-boot-demo-orm-mybatis
  2. > 此 demo 演示了 Spring Boot 如何与原生的 mybatis 整合,使用了 mybatis 官方提供的脚手架 `mybatis-spring-boot-starter `可以很容易的和 Spring Boot 整合。
  3. ## pom.xml
  4. ```xml
  5. <?xml version="1.0" encoding="UTF-8"?>
  6. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  8. <modelVersion>4.0.0</modelVersion>
  9. <artifactId>spring-boot-demo-orm-mybatis</artifactId>
  10. <version>1.0.0-SNAPSHOT</version>
  11. <packaging>jar</packaging>
  12. <name>spring-boot-demo-orm-mybatis</name>
  13. <description>Demo project for Spring Boot</description>
  14. <parent>
  15. <groupId>com.xkcoding</groupId>
  16. <artifactId>spring-boot-demo</artifactId>
  17. <version>1.0.0-SNAPSHOT</version>
  18. </parent>
  19. <properties>
  20. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  21. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  22. <java.version>1.8</java.version>
  23. <mybatis.version>1.3.2</mybatis.version>
  24. </properties>
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.mybatis.spring.boot</groupId>
  28. <artifactId>mybatis-spring-boot-starter</artifactId>
  29. <version>${mybatis.version}</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>mysql</groupId>
  33. <artifactId>mysql-connector-java</artifactId>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.projectlombok</groupId>
  37. <artifactId>lombok</artifactId>
  38. <optional>true</optional>
  39. </dependency>
  40. <dependency>
  41. <groupId>cn.hutool</groupId>
  42. <artifactId>hutool-all</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>com.google.guava</groupId>
  46. <artifactId>guava</artifactId>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. <scope>test</scope>
  52. </dependency>
  53. </dependencies>
  54. <build>
  55. <finalName>spring-boot-demo-orm-mybatis</finalName>
  56. <plugins>
  57. <plugin>
  58. <groupId>org.springframework.boot</groupId>
  59. <artifactId>spring-boot-maven-plugin</artifactId>
  60. </plugin>
  61. </plugins>
  62. </build>
  63. </project>
  64. ```
  65. ## SpringBootDemoOrmMybatisApplication.java
  66. ```java
  67. /**
  68. * <p>
  69. * 启动类
  70. * </p>
  71. *
  72. * @author yangkai.shen
  73. * @date Created in 2018-11-08 10:52
  74. */
  75. @MapperScan(basePackages = {"com.xkcoding.orm.mybatis.mapper"})
  76. @SpringBootApplication
  77. public class SpringBootDemoOrmMybatisApplication {
  78. public static void main(String[] args) {
  79. SpringApplication.run(SpringBootDemoOrmMybatisApplication.class, args);
  80. }
  81. }
  82. ```
  83. ## application.yml
  84. ```yaml
  85. spring:
  86. datasource:
  87. url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
  88. username: root
  89. password: root
  90. driver-class-name: com.mysql.cj.jdbc.Driver
  91. type: com.zaxxer.hikari.HikariDataSource
  92. initialization-mode: always
  93. continue-on-error: true
  94. schema:
  95. - "classpath:db/schema.sql"
  96. data:
  97. - "classpath:db/data.sql"
  98. hikari:
  99. minimum-idle: 5
  100. connection-test-query: SELECT 1 FROM DUAL
  101. maximum-pool-size: 20
  102. auto-commit: true
  103. idle-timeout: 30000
  104. pool-name: SpringBootDemoHikariCP
  105. max-lifetime: 60000
  106. connection-timeout: 30000
  107. logging:
  108. level:
  109. com.xkcoding: debug
  110. com.xkcoding.orm.mybatis.mapper: trace
  111. mybatis:
  112. configuration:
  113. # 下划线转驼峰
  114. map-underscore-to-camel-case: true
  115. mapper-locations: classpath:mappers/*.xml
  116. type-aliases-package: com.xkcoding.orm.mybatis.entity
  117. ```
  118. ## UserMapper.java
  119. ```java
  120. /**
  121. * <p>
  122. * User Mapper
  123. * </p>
  124. *
  125. * @author yangkai.shen
  126. * @date Created in 2018-11-08 10:54
  127. */
  128. @Mapper
  129. @Component
  130. public interface UserMapper {
  131. /**
  132. * 查询所有用户
  133. *
  134. * @return 用户列表
  135. */
  136. @Select("SELECT * FROM orm_user")
  137. List<User> selectAllUser();
  138. /**
  139. * 根据id查询用户
  140. *
  141. * @param id 主键id
  142. * @return 当前id的用户,不存在则是 {@code null}
  143. */
  144. @Select("SELECT * FROM orm_user WHERE id = #{id}")
  145. User selectUserById(@Param("id") Long id);
  146. /**
  147. * 保存用户
  148. *
  149. * @param user 用户
  150. * @return 成功 - {@code 1} 失败 - {@code 0}
  151. */
  152. int saveUser(@Param("user") User user);
  153. /**
  154. * 删除用户
  155. *
  156. * @param id 主键id
  157. * @return 成功 - {@code 1} 失败 - {@code 0}
  158. */
  159. int deleteById(@Param("id") Long id);
  160. }
  161. ```
  162. ## UserMapper.xml
  163. ```xml
  164. <?xml version="1.0" encoding="UTF-8"?>
  165. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  166. <mapper namespace="com.xkcoding.orm.mybatis.mapper.UserMapper">
  167. <insert id="saveUser">
  168. INSERT INTO `orm_user` (`name`,
  169. `password`,
  170. `salt`,
  171. `email`,
  172. `phone_number`,
  173. `status`,
  174. `create_time`,
  175. `last_login_time`,
  176. `last_update_time`)
  177. VALUES (#{user.name},
  178. #{user.password},
  179. #{user.salt},
  180. #{user.email},
  181. #{user.phoneNumber},
  182. #{user.status},
  183. #{user.createTime},
  184. #{user.lastLoginTime},
  185. #{user.lastUpdateTime})
  186. </insert>
  187. <delete id="deleteById">
  188. DELETE
  189. FROM `orm_user`
  190. WHERE `id` = #{id}
  191. </delete>
  192. </mapper>
  193. ```
  194. ## UserMapperTest.java
  195. ```java
  196. /**
  197. * <p>
  198. * UserMapper 测试类
  199. * </p>
  200. *
  201. * @author yangkai.shen
  202. * @date Created in 2018-11-08 11:25
  203. */
  204. @Slf4j
  205. public class UserMapperTest extends SpringBootDemoOrmMybatisApplicationTests {
  206. @Autowired
  207. private UserMapper userMapper;
  208. @Test
  209. public void selectAllUser() {
  210. List<User> userList = userMapper.selectAllUser();
  211. Assert.assertTrue(CollUtil.isNotEmpty(userList));
  212. log.debug("【userList】= {}", userList);
  213. }
  214. @Test
  215. public void selectUserById() {
  216. User user = userMapper.selectUserById(1L);
  217. Assert.assertNotNull(user);
  218. log.debug("【user】= {}", user);
  219. }
  220. @Test
  221. public void saveUser() {
  222. String salt = IdUtil.fastSimpleUUID();
  223. User user = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave3@xkcoding.com").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();
  224. int i = userMapper.saveUser(user);
  225. Assert.assertEquals(1, i);
  226. }
  227. @Test
  228. public void deleteById() {
  229. int i = userMapper.deleteById(1L);
  230. Assert.assertEquals(1, i);
  231. }
  232. }
  233. ```
  234. ## 参考
  235. - Mybatis官方文档:http://www.mybatis.org/mybatis-3/zh/index.html
  236. - Mybatis官方脚手架文档:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
  237. - Mybatis整合Spring Boot官方demo:https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples