I have been learning Java recently and found that mybatis appears quite frequently in Java recruitment, which may be the database ORM framework that is used more frequently in Java development. So I was going to study the integration of Spring Boot and mybatis.
1. Add the following configuration in the pom.xml file
<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> <!-- This is the official mybatis dependency. You can't use it without adding it --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- This is a dependency that automatically generates mappers, etc., must be added --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator</artifactId> <version>1.3.5</version> <type>pom</type> </dependency> <!--This is a dependency that automatically generates mappers, etc., and must be added 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> <!--Address for configuration file--> <!--<configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>--> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build>
2. Configure database and mybatis scanning in application.properties configuration file
spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/yddy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=123456mybatis.config-locations=classpath:mybatis-config.xml# mapper file mybatis.mapper-locations=classpath:mapper/*.xml #Write * directly here, which is beneficial for custom SQL and writing xxxExt.xml later. It automatically scans these files. There is no need to change the configuration mybatis.type-aliases-package=com.dameiweb.learn.modellogging.level.com.dameiweb.learn.dao=debug#mybatis.config = mybatis configuration file name#mybatis.mapperLocations = mapper xml file address#mybatis.typeAliasesPackage = entity class package path#mybatis.typeHandlersPackage = type handlers Processor package path#mybatis.check-config-location = check mybatis Whether the configuration exists, it is generally named mybatis-config.xml#mybatis.executorType = execution mode. Default is SIMPLE
3. Mybatis configuration and automatic mapper configuration
Create a new generatorConfig.xml and mybatis-config.xml in the resource directory. The content is as follows:
GeneratorConfig.xml content
<?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> <!--Database Link Address Account Password--> <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> <!--Generate Model class storage location--> <javaModelGenerator targetPackage="com.dameiweb.learn.model" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <!-- The spaces before and after the value returned from the database are cleaned --> <property name="trimStrings" value="false"/> </javaModelGenerator> <!-- Generate map file storage location--> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- Generate Dao class storage location--> <!-- Client code, generate easy-to-use code type="ANNOTATEDMAPPER", generate Java Model and annotation-based Mapper object type="MIXEDMAPPER", generate annotation-based Java Model and corresponding Mapper object type="XMLMAPPER", generate SQLMap XML files and independent Mapper interface--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.dameiweb.learn.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> </context></generatorConfiguration>
Contents of 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> <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>
In this way, we have configured Spring Boot, mybatis and mybatis to automatically generate mappers and entities. In this way, when we want to generate the entity and mapper of a certain table, we only need to add the following content after the javaClientGenerator tag in generatorConfig.xml.
Here we have the yd_movies table as an example (do not use plural numbers in the main database table name. This table name must be my brain before, so I made a plural name)
<!--Generate corresponding table and class name--> <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 uses this tag to prevent mybatis from generating xxxxWithBLOBs files when the database field type is text. -->
Then click Maven projects on the right side of idea, and you can see mybatis-generate: generate under mybatis-generate, and double-click mybatis-generate: generate.
**Generator Note, it can also be said to be a bug
It is when it is generated, and in the second generation, dao and entity will be directly overwritten, while Mapper.xml will be directly appended, resulting in an error in the run and it is difficult to find. **
4.mybatis custom sql
When we need to customize SQL, we cannot put these into the mapper file as well. Otherwise, when the fields of the database table are updated and need to be regenerated, will our customized SQL be overwritten? So we need to create a new MovieMapperExt.xml file in the directory of MovieMapper.xml and put the custom SQL here. The example is as follows:
MovieMapperExt.xml file content
<?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.dmeiweb.learn.dao.MovieMapper" > <select id="selectByCondition" resultMap="BaseResultMap" parameterType="com.dmeiweb.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>Summarize
The above is the Spring Boot introduced to you by the editor. It integrates mybatis and automatically generates mappers and entities. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!