转载

Spring Boot整合mybatis,并自动生成mapper和实体

最近一直都在学习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>

最后更新于 2018-05-07 14:54:16 并被添加「spring boot mybatis」标签,已有 1 位童鞋阅读过。

原文  https://www.ydstudio.net/archives/54.html
正文到此结束
Loading...