1.前言

Springboot最近可谓是非常的火,本人也在项目中尝到了甜头。之前一直使用Springboot+JPA,用了一段时间发现JPA不是太灵活,也有可能是我不精通JPA,总之为了多学学Springboot我决定尝试一下Springboot+MyBatis+JPA三项集成,集成过程中遇到了很多问题,但最后总算是集成成功了,现在记录一下方法。

1.1 如何使用MyBatis Generator自动生成xxxMapper.java接口以及xxxMapper.xml文件

以前用过SpringMVC,知道写xxxMapper.java接口以及xxxMapper.xml文件的辛苦,这次集成最先想到的就是先解决如何使用如何使用MyBatis Generator自动生成这些文件的问题。

先扔出MyBatis Generator的官网->请戳这里

我使用的Maven集成插件的方式,IDE使用的是IDEA

1.1.1 创建项目

 
20180126110629.png
 
20180126110757.png
 
20180126110812.png

1.1.2 修改pom.xml

添加了Druid依赖和MyBatis Generator插件

其他依赖请自行添加

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.study.springboot</groupId>
  6. <artifactId>mybatis</artifactId>
  7. <version>1.0</version>
  8. <packaging>war</packaging>
  9. <name>demo</name>
  10. <description>springboot+mybatis+jpa</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>1.5.9.RELEASE</version>
  15. <relativePath/>
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-data-jpa</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.mybatis.spring.boot</groupId>
  29. <artifactId>mybatis-spring-boot-starter</artifactId>
  30. <version>1.3.1</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-web</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>mysql</groupId>
  38. <artifactId>mysql-connector-java</artifactId>
  39. <scope>runtime</scope>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter-tomcat</artifactId>
  44. <!--<scope>provided</scope>-->
  45. </dependency>
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. <!-- 阿里巴巴连接池Druid -->
  52. <dependency>
  53. <groupId>com.alibaba</groupId>
  54. <artifactId>druid</artifactId>
  55. <version>1.1.5</version>
  56. </dependency>
  57. </dependencies>
  58. <build>
  59. <plugins>
  60. <plugin>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-maven-plugin</artifactId>
  63. </plugin>
  64. <!-- MyBatis Generator 插件 -->
  65. <plugin>
  66. <groupId>org.mybatis.generator</groupId>
  67. <artifactId>mybatis-generator-maven-plugin</artifactId>
  68. <version>1.3.5</version>
  69. <executions>
  70. <execution>
  71. <id>Generate MyBatis Artifacts</id>
  72. <goals>
  73. <goal>generate</goal>
  74. </goals>
  75. </execution>
  76. </executions>
  77. </plugin>
  78. </plugins>
  79. </build>
  80. </project>

1.1.3 配置generatorConfiguration

generatorConfig.xml放在resource文件夹下

常用配置已经注释了,请自行查看

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <!--
  7. 可以用于加载配置项或者配置文件,在整个配置文件中就可以使用${propertyKey}的方式来引用配置项
  8. resource:配置资源加载地址,使用resource,MBG从classpath开始找,比如com/myproject/generatorConfig.properties
  9. url:配置资源加载地址,使用URL的方式,比如file:///C:/myfolder/generatorConfig.properties
  10. 注意,两个属性只能选址一个
  11. 另外,如果使用了mybatis-generator-maven-plugin,那么在pom.xml中定义的properties都可以直接在generatorConfig.xml中使用
  12. <properties resource="" url="" />
  13. -->
  14. <!--<properties resource="db.properties"/>-->
  15. <!--
  16. 在MBG工作的时候,需要额外加载的依赖包
  17. location属性指明加载jar/zip包的全路径
  18. -->
  19. <classPathEntry
  20. location="C:\Users\Semi\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar"/>
  21. <!--
  22. context:生成一组对象的环境
  23. id:必选,上下文id,用于在生成错误时提示
  24. defaultModelType:指定生成对象的样式
  25. 1. conditional:类似hierarchical
  26. 2. flat:所有内容(主键,blob)等全部生成在一个对象中
  27. 3. hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class)
  28. targetRuntime:
  29. 1. MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample
  30. 2. MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample
  31. introspectedColumnImpl:类全限定名,用于扩展MBG
  32. -->
  33. <context id="MyBatis" targetRuntime="MyBatis3">
  34. <!--
  35. 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表
  36. 一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖
  37. -->
  38. <property name="autoDelimitKeywords" value="false"/>
  39. <!-- 生成的Java文件的编码 -->
  40. <property name="javaFileEncoding" value="UTF-8"/>
  41. <!-- 格式化Java代码 -->
  42. <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
  43. <!-- 格式化XML代码 -->
  44. <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
  45. <!-- 不生成注释 -->
  46. <commentGenerator>
  47. <property name="suppressAllComments" value="true"/>
  48. <property name="suppressDate" value="true"/>
  49. </commentGenerator>
  50. <!-- JDBC连接配置 -->
  51. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  52. connectionURL="jdbc:mysql://localhost:3306/test"
  53. userId="root"
  54. password="123456"/>
  55. <!--
  56. Java类型处理器
  57. 用于处理DB中的类型到Java中的类型,默认使用JavaTypeResolverDefaultImpl
  58. 注意一点,默认会先尝试使用Integer,Long,Short等来对应DECIMAL和NUMERIC数据类型
  59. -->
  60. <javaTypeResolver>
  61. <!--
  62. true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型
  63. false:默认
  64. scale>0;length>18:使用BigDecimal
  65. scale=0;length[10,18]:使用Long
  66. scale=0;length[5,9]:使用Integer
  67. scale=0;length<5:使用Short
  68. -->
  69. <property name="forceBigDecimals" value="false"/>
  70. </javaTypeResolver>
  71. <!--
  72. Java模型创建器,是必须要的元素
  73. 负责:
  74. 1. key类(见context的defaultModelType)
  75. 2. java类
  76. 3. 查询类
  77. targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制
  78. targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录
  79. -->
  80. <javaModelGenerator targetPackage="com.study.springboot.mybatis.model"
  81. targetProject="E:\WorkSpace\study\springboot\mybatis\src\main\java">
  82. <!-- 自动为每一个生成的类创建一个构造方法,构造方法包含了所有的field,而不是使用setter -->
  83. <!--<property name="constructorBased" value="false"/>-->
  84. <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
  85. <property name="enableSubPackages" value="false"/>
  86. <!--
  87. 是否创建一个不可变的类,如果为true
  88. 那么MBG会创建一个没有setter方法的类,取而代之的是类似constructorBased的类
  89. -->
  90. <!--<property name="immutable" value="false"/>-->
  91. <!--
  92. 设置一个根对象
  93. 如果设置了这个根对象,那么生成的keyClass或者recordClass会继承这个类,在Table的rootClass属性中可以覆盖该选项
  94. 注意:
  95. 如果在key class或者record class中有root class相同的属性,MBG就不会重新生成这些属性了,包括:
  96. 1. 属性名相同,类型相同,有相同的getter/setter方法
  97. -->
  98. <!--<property name="rootClass" value="com._520it.mybatis.domain.BaseDomain"/>-->
  99. <!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
  100. <property name="trimStrings" value="true"/>
  101. </javaModelGenerator>
  102. <!--
  103. 生成SQL map的XML文件生成器
  104. 注意,在Mybatis3之后,我们可以使用mapper.xml文件+Mapper接口(或者不用mapper接口)
  105. 或者只使用Mapper接口+Annotation,所以,如果javaClientGenerator配置中配置了需要生成XML的话,这个元素就必须配置
  106. targetPackage/targetProject:同javaModelGenerator
  107. -->
  108. <sqlMapGenerator targetPackage="mapper"
  109. targetProject="E:\WorkSpace\study\springboot\mybatis\src\main\resources">
  110. <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
  111. <property name="enableSubPackages" value="false"/>
  112. </sqlMapGenerator>
  113. <!--
  114. 对于mybatis来说,即生成Mapper接口
  115. 注意,如果没有配置该元素,那么默认不会生成Mapper接口
  116. targetPackage/targetProject:同javaModelGenerator
  117. type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下)
  118. 1. ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中)不会生成对应的XML
  119. 2. MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中
  120. 3. XMLMAPPER:会生成Mapper接口,接口完全依赖XML
  121. 注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
  122. -->
  123. <javaClientGenerator type="XMLMAPPER" targetPackage="com.study.springboot.mybatis.mapper"
  124. targetProject="E:\WorkSpace\study\springboot\mybatis\src\main\java">
  125. <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
  126. <property name="enableSubPackages" value="false"/>
  127. <!--
  128. 可以为所有生成的接口添加一个父接口,但是MBG只负责生成,不负责检查
  129. <property name="rootInterface" value=""/>
  130. -->
  131. </javaClientGenerator>
  132. <!--
  133. 选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
  134. 选择的table会生成一下文件:
  135. 1. SQL map文件
  136. 2. 生成一个主键类
  137. 3. 除了BLOB和主键的其他字段的类
  138. 4. 包含BLOB的类
  139. 5. 一个用户生成动态查询的条件类(selectByExample, deleteByExample)可选
  140. 6. Mapper接口(可选)
  141. tableName(必要):要生成对象的表名,%表示通配,即为该数据库下的所有表生成xml文件
  142. 注意:大小写敏感问题.正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下
  143. MBG会根据设置的schema,catalog或tablename去查询数据表,按照下面的流程:
  144. 1. 如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询
  145. 2. 否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找
  146. 3. 否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找
  147. 4. 否则,使用指定的大小写格式查询
  148. 另外,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名
  149. 这个时候,请设置delimitIdentifiers="true"即可保留大小写格式
  150. 可选:
  151. 1. schema:数据库的schema
  152. 2. catalog:数据库的catalog
  153. 3. alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName
  154. 4. domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面
  155. 5. enableInsert(默认true):指定是否生成insert语句
  156. 6. enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get)
  157. 7. enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句
  158. 8. enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update)
  159. 9. enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete)
  160. 10. enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句
  161. 11. enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询)
  162. 12. enableUpdateByExample(默认true)MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性)
  163. 13. modelType:参考context元素的defaultModelType,相当于覆盖
  164. 14. delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性)
  165. 15. delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来.默认为false,delimitIdentifiers参考context的属性
  166. 注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写
  167. -->
  168. <table tableName="%"
  169. enableCountByExample="false"
  170. enableUpdateByExample="false"
  171. enableDeleteByExample="false"
  172. enableSelectByExample="false"
  173. selectByExampleQueryId="false">
  174. <!-- 参考javaModelGenerator的constructorBased属性 -->
  175. <!--<property name="constructorBased" value="false"/>-->
  176. <!-- 默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema -->
  177. <!--<property name="ignoreQualifiersAtRuntime" value="false"/>-->
  178. <!-- 参考javaModelGenerator的immutable属性 -->
  179. <!--<property name="immutable" value="false"/>-->
  180. <!-- 指定是否只生成domain类,如果设置为true,只生成domain类,如果还配置了sqlMapGenerator,那么在mapper XML文件中,只生成resultMap元素 -->
  181. <!--<property name="modelOnly" value="false"/>-->
  182. <!-- 参考javaModelGenerator的rootClass属性 -->
  183. <!--<property name="rootClass" value=""/>-->
  184. <!-- 参考javaClientGenerator的rootInterface属性 -->
  185. <!--<property name="rootInterface" value=""/>-->
  186. <!-- 如果设置了runtimeCatalog,那么在生成的SQL中,使用该指定的catalog,而不是table元素上的catalog -->
  187. <!--<property name="runtimeCatalog" value=""/>-->
  188. <!-- 如果设置了runtimeSchema,那么在生成的SQL中,使用该指定的schema,而不是table元素上的schema -->
  189. <!--<property name="runtimeSchema" value=""/>-->
  190. <!-- 如果设置了runtimeTableName,那么在生成的SQL中,使用该指定的tablename,而不是table元素上的tablename -->
  191. <!--<property name="runtimeTableName" value=""/>-->
  192. <!--
  193. 注意,该属性只针对MyBatis3Simple有用
  194. 如果选择的runtime是MyBatis3Simple,那么会生成一个SelectAll方法,如果指定了selectAllOrderByClause,那么会在该SQL中添加指定的这个order条件
  195. -->
  196. <!--<property name="selectAllOrderByClause" value="age desc,username asc"/>-->
  197. <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是bornDate -->
  198. <!--<property name="useActualColumnNames" value="false"/>-->
  199. <!--
  200. generatedKey用于生成生成主键的方法
  201. 如果设置了该元素,MBG会在生成的<insert>元素中生成一条正确的<selectKey>元素,该元素可选
  202. column:主键的列名
  203. sqlStatement:要生成的selectKey语句,有以下可选项:
  204. Cloudscape:相当于selectKey的SQL为:VALUES IDENTITY_VAL_LOCAL()
  205. DB2 :相当于selectKey的SQL为:VALUES IDENTITY_VAL_LOCAL()
  206. DB2_MF :相当于selectKey的SQL为:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
  207. Derby :相当于selectKey的SQL为:VALUES IDENTITY_VAL_LOCAL()
  208. HSQLDB :相当于selectKey的SQL为:CALL IDENTITY()
  209. Informix :相当于selectKey的SQL为:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
  210. MySql :相当于selectKey的SQL为:SELECT LAST_INSERT_ID()
  211. SqlServer :相当于selectKey的SQL为:SELECT SCOPE_IDENTITY()
  212. SYBASE :相当于selectKey的SQL为:SELECT @@IDENTITY
  213. JDBC :相当于在生成的insert元素上添加useGeneratedKeys="true"和keyProperty属性
  214. -->
  215. <!--<generatedKey column="" sqlStatement=""/>-->
  216. <!--
  217. 该元素会在根据表中列名计算对象属性名之前先重命名列名,非常适合用于表中的列都有公用的前缀字符串的时候
  218. 比如列名为:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等
  219. 那么就可以设置searchString为"^CUST_",并使用空白替换,那么生成的Customer对象中的属性名称就不是
  220. custId,custName等,而是先被替换为ID,NAME,EMAIL,然后变成属性:id,name,email
  221. 注意,MBG是使用java.util.regex.Matcher.replaceAll来替换searchString和replaceString的
  222. 如果使用了columnOverride元素,该属性无效
  223. -->
  224. <!--<columnRenamingRule searchString="" replaceString=""/>-->
  225. <!--
  226. 用来修改表中某个列的属性,MBG会使用修改后的列来生成domain的属性
  227. column:要重新设置的列名
  228. 注意,一个table元素中可以有多个columnOverride元素
  229. -->
  230. <!--<columnOverride column="username">-->
  231. <!-- 使用property属性来指定列要生成的属性名称 -->
  232. <!--<property name="property" value="userName"/>-->
  233. <!-- javaType用于指定生成的domain的属性类型,使用类型的全限定名 -->
  234. <!--<property name="javaType" value=""/>-->
  235. <!-- jdbcType用于指定该列的JDBC类型 -->
  236. <!--<property name="jdbcType" value=""/>-->
  237. <!--
  238. typeHandler:用于指定该列使用到的TypeHandler,如果要指定,配置类型处理器的全限定名
  239. 注意,mybatis中,不会生成到mybatis-config.xml中的typeHandler
  240. 只会生成类似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的参数描述
  241. -->
  242. <!--<property name="jdbcType" value=""/>-->
  243. <!-- 参考table元素的delimitAllColumns配置,默认为false -->
  244. <!--<property name="delimitedColumnName" value=""/>-->
  245. <!--
  246. ignoreColumn设置一个MGB忽略的列,如果设置了改列,那么在生成的domain中,生成的SQL中,都不会有该列出现
  247. column:指定要忽略的列的名字
  248. delimitedColumnName:参考table元素的delimitAllColumns配置,默认为false
  249. 注意,一个table元素中可以有多个ignoreColumn元素
  250. -->
  251. <!--<ignoreColumn column="deptId" delimitedColumnName=""/>-->
  252. </table>
  253. </context>
  254. </generatorConfiguration>

1.1.4 生成xxxMapper.java接口以及xxxMapper.xml文件

 
20180126111603.png

注意,如果存放xxxMapper.java和xxxMapper.xml文件的包不存在会报错

1.1.5 修改自动生成的实体类

对于model包下的实体类需要添加基于JPA的注解,否则JPA接口无法引用

例如对于User.java实体类需要进行如下修改


  1. package com.study.springboot.mybatis.model;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name = "user")
  5. public class User {
  6. @Id
  7. @GeneratedValue
  8. @Column(name = "id")
  9. private Integer id;
  10. @Column(name = "user_name")
  11. private String userName;
  12. @Column(name = "passwd")
  13. private String passwd;
  14. @Column(name = "nick_name")
  15. private String nickName;
  16. @Column(name = "telephone")
  17. private String telephone;
  18. @Column(name = "email")
  19. private String email;
  20. @Column(name = "authority")
  21. private Integer authority;
  22. @Column(name = "department")
  23. private String department;
  24. @Column(name = "create_at")
  25. private String createAt;
  26. @Column(name = "update_at")
  27. private String updateAt;
  28. public Integer getId() {
  29. return id;
  30. }
  31. public void setId(Integer id) {
  32. this.id = id;
  33. }
  34. public String getUserName() {
  35. return userName;
  36. }
  37. public void setUserName(String userName) {
  38. this.userName = userName == null ? null : userName.trim();
  39. }
  40. public String getPasswd() {
  41. return passwd;
  42. }
  43. public void setPasswd(String passwd) {
  44. this.passwd = passwd == null ? null : passwd.trim();
  45. }
  46. public String getNickName() {
  47. return nickName;
  48. }
  49. public void setNickName(String nickName) {
  50. this.nickName = nickName == null ? null : nickName.trim();
  51. }
  52. public String getTelephone() {
  53. return telephone;
  54. }
  55. public void setTelephone(String telephone) {
  56. this.telephone = telephone == null ? null : telephone.trim();
  57. }
  58. public String getEmail() {
  59. return email;
  60. }
  61. public void setEmail(String email) {
  62. this.email = email == null ? null : email.trim();
  63. }
  64. public Integer getAuthority() {
  65. return authority;
  66. }
  67. public void setAuthority(Integer authority) {
  68. this.authority = authority;
  69. }
  70. public String getDepartment() {
  71. return department;
  72. }
  73. public void setDepartment(String department) {
  74. this.department = department == null ? null : department.trim();
  75. }
  76. public String getCreateAt() {
  77. return createAt;
  78. }
  79. public void setCreateAt(String createAt) {
  80. this.createAt = createAt == null ? null : createAt.trim();
  81. }
  82. public String getUpdateAt() {
  83. return updateAt;
  84. }
  85. public void setUpdateAt(String updateAt) {
  86. this.updateAt = updateAt == null ? null : updateAt.trim();
  87. }
  88. }

1.1.6 添加xxxJPA接口,例如UserJPA.java


  1. import org.springframework.data.jpa.repository.JpaRepository;
  2. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  3. import java.io.Serializable;
  4. public interface UserJPA extends
  5. Serializable,
  6. JpaRepository<User, Integer>,
  7. JpaSpecificationExecutor<User> {
  8. }

1.1.7 测试

测试之前需要配置application.yml(你的有能是application.properties,改一下后缀名即可,我比较喜欢.yml文件的简洁)

  1. spring:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource
  4. url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
  5. driver-class-name: com.mysql.jdbc.Driver
  6. username: root
  7. password: 123456
  8. mybatis:
  9. # 重要配置
  10. type-aliases-package: com.study.springboot.mybatis.model
  11. mapper-locations: classpath:mapper/*.xml

对于每一个xxxMapper.java接口,需要使用@Component注解

自动生成的xxxMapper.java接口是不带@Component注解的

  1. @Component
  2. public interface UserMapper {
  3. int deleteByPrimaryKey(Integer id);
  4. int insert(User record);
  5. int insertSelective(User record);
  6. User selectByPrimaryKey(Integer id);
  7. int updateByPrimaryKeySelective(User record);
  8. int updateByPrimaryKey(User record);
  9. }

在入口类中需要添加@MapperScan("com.study.springboot.mybatis.mapper")注解

  1. @SpringBootApplication
  2. @MapperScan("com.study.springboot.mybatis.mapper")
  3. public class MybatisApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(MybatisApplication.class, args);
  6. }
  7. }

打开测试类,为测试类添加@MapperScan("com.study.springboot.mybatis.mapper")注解

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. @MapperScan("com.study.springboot.mybatis.mapper")
  4. public class MybatisApplicationTests {
  5. @Autowired
  6. private UserMapper userMapper;
  7. @Autowired
  8. private UserJPA userJPA;
  9. @Test
  10. public void contextLoads() {
  11. System.out.println(userMapper.selectByPrimaryKey(11).getUserName());
  12. System.out.println(userJPA.findOne(11).getUserName());
  13. }
  14. }
 
20180126110153.png

最后如果出现

  1. java.lang.NoClassDefFoundError: org/apache/ibatis/session/SqlSession

的错误,请检查本地Maven仓库的配置,有可能是没有Maven没有下载需要引用的包

Springboot+MyBatis+JPA集成的更多相关文章

  1. 集成Springboot+MyBatis+JPA

    1.前言 Springboot最近可谓是非常的火,本人也在项目中尝到了甜头.之前一直使用Springboot+JPA,用了一段时间发现JPA不是太灵活,也有可能是我不精通JPA,总之为了多学学Spri ...

  2. SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)

    SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...

  3. SpringBoot | 第三十五章:Mybatis的集成和使用

    前言 最近收到公众号留言说,单纯的Mybatis的集成和使用.前面在第九章:Mybatis-plus的集成和使用介绍了基于mybatis-plus的集成和使用.后者也只是对mybatis进行了功能增强 ...

  4. SpringBoot系列之集成Mybatis教程

    SpringBoot系列之集成Mybatis教程 环境准备:IDEA + maven 本博客通过例子的方式,介绍Springboot集成Mybatis的两种方法,一种是通过注解实现,一种是通过xml的 ...

  5. SpringBoot系列之Spring Data Jpa集成教程

    SpringBoot系列之Spring Data Jpa集成教程 Spring Data Jpa是属于Spring Data的一个子项目,Spring data项目是一款集成了很多数据操作的项目,其下 ...

  6. 记一次springboot+mybatis+phoenix在代码集成中的坑

    场景: 希望使用phoenix做查询服务,给服务端提供接口 设计: 通过springboot做restful的接口发布,通过mybatis做phoenix的sql处理,因此是springboot+my ...

  7. springboot+mybatis集成多数据源MySQL/Oracle/SqlServer

    日常开发中可能时常会遇到一些这样的需求,业务数据库和第三方数据库,两个或多个数据库属于不同数据库厂商,这时候就需要通过配置来实现对数据库实现多源处理.大致说一下我的业务场景,框架本身是配置的sprin ...

  8. springboot 零xml集成mybatis

    maven依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  9. 第五章 springboot + mybatis(转载)

    本编博客转发自:http://www.cnblogs.com/java-zhao/p/5350021.html springboot集成了springJDBC与JPA,但是没有集成mybatis,所以 ...

随机推荐

  1. Django学习手册 - 登录验证码

    生成验证码函数 import random from PIL import Image, ImageDraw, ImageFont, ImageFilter _letter_cases = " ...

  2. Django学习手册 - ORM sqlit基础数据库操作

    步骤阐述:( splitDB 是Django自带的一个数据库) 1.在APP01 中的 models.py 配置DB信息  userinfo 相当于数据表的表名,而 uname.pwd 相当于 表中的 ...

  3. Callable的用法示例

    //Runnable是执行工作的独立任务,但是它不返回任何值.在JavaSE5中引入的Callable是一种具有类型参数的泛型,它的类型参数表的是从方法call()中返回的值,并且必须使用Execut ...

  4. SQL Server - NOLOCK

    NOLOCK 一般用于此类语句中:select * from t with(NOLOCK)nolock是不加锁查询,可以读取被事务锁定的数据,也称为脏读.说明:使当前会话的查询,不受其它会话的事务所阻 ...

  5. MySql联合查询

    将多条查询语句的结果合并为一个结果 *多表查询是横向连接,联合查询是纵向连接. 语法: 查询语句1 union 查询语句2 union 查询语句3 *union关键字默认去重,union all包含重 ...

  6. Cascade R-CNN论文讲解(转载)

    转载链接:https://blog.csdn.net/qq_21949357/article/details/80046867 论文思想:为了解决IOU设置带来的最终的AP值,作者引入了cascade ...

  7. LwIP Application Developers Manual1---介绍

    1.前言 本文主要是对LwIP Application Developers Manual的翻译 2.读者(应用开发手册的读者) 谁适合读这份手册 网络应用的开发者 想了解lwIP的网络应用开发者 阅 ...

  8. Content-Type的几种常用数据编码格式

    Content-Type,内容类型,一般是指网页中存在的Content-Type,ContentType属性指定请求和响应的HTTP内容类型.如果未指定 ContentType,默认为text/htm ...

  9. MYSQL在centos上主从配置

    主从配置理论传送门:http://blog.csdn.net/hguisu/article/details/7325124 具体配置方案: 一:MYSQL主从配置   1.1 部署环境 主(maste ...

  10. Linux虚拟串口

    将下列Python代码保存成VitrualCom.py: Code#! /usr/bin/env python #coding=utf-8 import pty import os import se ...