欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-10 15:28:34
最近一直都在学习java,发现目前java招聘中,mybatis出现的频率挺高的,可能是目前java开发中使用比较多的数据库orm框架。于是我准备研究下spring boo...

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

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

<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扫描的配置

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内容

<?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的内容:

<?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表为例(主要数据库表名字不要用复数,这个表名肯定是我之前脑子抽了,搞个复数的名字)

<!--生成对应表及类名-->
  <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文件内容

<?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和实体,希望对大家有所帮助