Spring Boot整合mybatis并自动生成mapper和实体实例解析

时间:2022-09-04 21:50:23

最近一直都在学习java,发现目前java招聘中,mybatis出现的频率挺高的,可能是目前java开发中使用比较多的数据库orm框架。于是我准备研究下spring boot和mybatis的整合。

1.在pom.xml文件中添加下面的配置

?
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<dependencies>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-web</artifactid>
  </dependency>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-test</artifactid>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-jdbc</artifactid>
  </dependency>
  <dependency>
   <groupid>mysql</groupid>
   <artifactid>mysql-connector-java</artifactid>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupid>com.alibaba</groupid>
   <artifactid>druid</artifactid>
   <version>1.0.29</version>
  </dependency>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-data-jpa</artifactid>
  </dependency>
 <!-- 这个是官方的mybatis依赖,这个你不加没法用噻 -->
  <dependency>
   <groupid>org.mybatis.spring.boot</groupid>
   <artifactid>mybatis-spring-boot-starter</artifactid>
   <version>1.3.2</version>
  </dependency>
  <!-- 这个是自动生成mapper等的依赖,必须得加-->
  <dependency>
   <groupid>org.mybatis.generator</groupid>
   <artifactid>mybatis-generator</artifactid>
   <version>1.3.5</version>
   <type>pom</type>
  </dependency>
  <!--这个是自动生成mapper等的依赖,必须得加 https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
  <dependency>
   <groupid>org.mybatis.generator</groupid>
   <artifactid>mybatis-generator-core</artifactid>
   <version>1.3.5</version>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-maven-plugin</artifactid>
   </plugin>
   <plugin>
    <groupid>org.mybatis.generator</groupid>
    <artifactid>mybatis-generator-maven-plugin</artifactid>
    <version>1.3.2</version>
    <configuration>
     <!--配置文件存放的地址-->
     <!--<configurationfile>src/main/resources/mybatis-generator/generatorconfig.xml</configurationfile>-->
     <verbose>true</verbose>
     <overwrite>true</overwrite>
    </configuration>
   </plugin>
  </plugins>
 </build>

2.在application.properties配置文件中进行数据库和mybatis扫描的配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
spring.datasource.driver-class-name=com.mysql.jdbc.driver
spring.datasource.url=jdbc:mysql://localhost:3306/yddy?useunicode=true&characterencoding=utf-8&servertimezone=utc
spring.datasource.username=root
spring.datasource.password=123456
mybatis.config-locations=classpath:mybatis-config.xml
# mapper文件
mybatis.mapper-locations=classpath:mapper/*.xml #这里直接写*,对后面自定义sql,编写xxxext.xml有好处,自动扫描到这些文件,不用再改配置了
mybatis.type-aliases-package=com.dameiweb.learn.model
logging.level.com.dameiweb.learn.dao=debug
#mybatis.config = mybatis 配置文件名称
#mybatis.mapperlocations = mapper xml 文件地址
#mybatis.typealiasespackage = 实体类包路径
#mybatis.typehandlerspackage = type handlers 处理器包路径
#mybatis.check-config-location = 检查 mybatis 配置是否存在,一般命名为 mybatis-config.xml
#mybatis.executortype = 执行模式。默认是 simple

3.mybatis的配置和自动生成mapper的配置

在resource目录下新建一个generatorconfig.xml和mybatis-config.xml。内容如下:

generatorconfig.xml内容

?
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
<?xml version="1.0" encoding="utf-8"?>
<!doctype generatorconfiguration
  public "-//mybatis.org//dtd mybatis generator configuration 1.0//en"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorconfiguration>
 <classpathentry location="c:\users\nick\.m2\repository/mysql/mysql-connector-java/5.1.46/mysql-connector-java-5.1.46.jar"/>
 <context id="db2tables" targetruntime="mybatis3">
  <commentgenerator>
   <property name="suppressdate" value="true"/>
   <property name="suppressallcomments" value="true"/>
  </commentgenerator>
  <!--数据库链接地址账号密码-->
  <jdbcconnection driverclass="com.mysql.jdbc.driver" connectionurl="jdbc:mysql://localhost:3306/yddy?useunicode=true&characterencoding=utf-8&servertimezone=utc" userid="root" password="123456">
  </jdbcconnection>
  <javatyperesolver>
   <property name="forcebigdecimals" value="false"/>
  </javatyperesolver>
  <!--生成model类存放位置-->
  <javamodelgenerator targetpackage="com.dameiweb.learn.model" targetproject="src/main/java">
   <property name="enablesubpackages" value="true"/>
   <!-- 从数据库返回的值被清理前后的空格 -->
   <property name="trimstrings" value="false"/>
  </javamodelgenerator>
  <!--生成映射文件存放位置-->
  <sqlmapgenerator targetpackage="mapper" targetproject="src/main/resources">
   <property name="enablesubpackages" value="true"/>
  </sqlmapgenerator>
  <!--生成dao类存放位置-->
  <!-- 客户端代码,生成易于使用的针对model对象和xml配置文件 的代码
    type="annotatedmapper",生成java model 和基于注解的mapper对象
    type="mixedmapper",生成基于注解的java model 和相应的mapper对象
    type="xmlmapper",生成sqlmap xml文件和独立的mapper接口
  -->
  <javaclientgenerator type="xmlmapper" targetpackage="com.dameiweb.learn.dao" targetproject="src/main/java">
   <property name="enablesubpackages" value="true"/>
  </javaclientgenerator>
 </context>
</generatorconfiguration>

mybatis-config.xml的内容:

?
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
<?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="callsettersonnulls" value="true"/>
  <setting name="cacheenabled" value="true"/>
  <setting name="lazyloadingenabled" value="true"/>
  <setting name="aggressivelazyloading" value="true"/>
  <setting name="multipleresultsetsenabled" value="true"/>
  <setting name="usecolumnlabel" value="true"/>
  <setting name="usegeneratedkeys" value="false"/>
  <setting name="automappingbehavior" value="partial"/>
  <setting name="defaultexecutortype" value="simple"/>
  <setting name="mapunderscoretocamelcase" value="true"/>
  <setting name="localcachescope" value="session"/>
  <setting name="jdbctypefornull" value="null"/>
 </settings>
 <typealiases>
  <typealias alias="integer" type="java.lang.integer" />
  <typealias alias="long" type="java.lang.long" />
  <typealias alias="hashmap" type="java.util.hashmap" />
  <typealias alias="linkedhashmap" type="java.util.linkedhashmap" />
  <typealias alias="arraylist" type="java.util.arraylist" />
  <typealias alias="linkedlist" type="java.util.linkedlist" />
 </typealiases>
</configuration>

这样我们就配置好了spring boot和mybatis与mybatis自动生成mapper和实体的功能。这样我们要生成某个表的实体和mapper的时候,只需要在generatorconfig.xml中javaclientgenerator标签之后添加下面的内容即可。

此处我们已yd_movies表为例(主要数据库表名字不要用复数,这个表名肯定是我之前脑子抽了,搞个复数的名字)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<!--生成对应表及类名-->
  <table tablename="yd_movies" domainobjectname="movie" enablecountbyexample="false" enableupdatebyexample="false"
    enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false">
   <columnoverride column="cover_photos" javatype="java.lang.string" jdbctype="varchar" />
   <columnoverride column="cover_photos_loc" javatype="java.lang.string" jdbctype="varchar" />
   <columnoverride column="pubdates" javatype="java.lang.string" jdbctype="varchar" />
   <columnoverride column="photographs_origin" javatype="java.lang.string" jdbctype="varchar" />
   <columnoverride column="photographs_origin_loc" javatype="java.lang.string" jdbctype="varchar" />
   <columnoverride column="languages" javatype="java.lang.string" jdbctype="varchar" />
   <columnoverride column="awards" javatype="java.lang.string" jdbctype="varchar" />
   <columnoverride column="summary" javatype="java.lang.string" jdbctype="varchar" />
  </table>
<!--columnoverride使用这个标签是为了防止数据库字段类型为text时候,mybatis会生成xxxxwithblobs文件。-->

然后点击idea右侧maven projects,就可以看到mybatis-generate下的mybatis-generate:generate,双击mybatis-generate:generate即可。

**generator 注意点,也可以说是bug

就是在生成的时候,在第二次生成的时候,dao 和entity 都会直接覆盖,而mapper.xml 会直接追加,导致运行报错,而且很难找。**

4.mybatis自定义sql

当我们需要自定义sql的时候,我们不能把这些也放到mapper文件中。不然,当数据库表的字段有更新需要重新生成mapper的时候,这样我们自定义的sql不就被覆盖没了么!所以我们需要在moviemapper.xml的同级目录里,新建一个moviemapperext.xml文件,把自定义的sql放到这里,例子如下:

moviemapperext.xml文件内容

?
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
<?xml version="1.0" encoding="utf-8" ?>
<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.dameiweb.learn.dao.moviemapper" >
 <select id="selectbycondition" resultmap="baseresultmap" parametertype="com.dameiweb.learn.dto.movierequest">
 select yd_movies.* from yd_movies
 left join yd_r_movie_countries on yd_movies.id = yd_r_movie_countries.movie_id
 left join yd_countries cou on yd_r_movie_countries.country_id = cou.id
 left join yd_r_movie_category on yd_movies.id = yd_r_movie_category.movie_id
 left join yd_category cat on yd_r_movie_category.category_id = cat.id
 left join yd_r_movie_actor on yd_movies.id = yd_r_movie_actor.movie_id
 left join yd_actors a on yd_r_movie_actor.actor_id = a.id
 where
 yd_movies.status = 1
 <if test="movierequest.title != null">
  and yd_movies.title like "%"#{movierequest.title}"%"
 </if>
 <if test="movierequest.country != null">
  and cou.id = #{movierequest.country}
 </if>
 <if test="movierequest.category != null">
  and cat.id = #{movierequest.category}
 </if>
 <if test="movierequest.year != null">
  and year = #{movierequest.year}
 </if>
 <if test="movierequest.rate != null">
  and rate >= #{movierequest.rate}
 </if>
 <if test="movierequest.rate != null">
  and rate < (#{movierequest.rate}+1)
 </if>
 <if test="movierequest.subtype != null">
  and yd_movies.subtype = #{movierequest.subtype}
 </if>
 group by yd_movies.id
 order by updated_at desc, year
 </select>
</mapper>

总结

以上所述是小编给大家介绍的spring boot整合mybatis并自动生成mapper和实体,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.ydstudio.net/archives/54.html