This article describes how to use Maven and Mybatis-generator together.
Brief introduction
Mybatis-generator is a convenient plug-in provided by Mybatis, which can automatically produce the corresponding entity class, Mapper,dao layer for the project.
Official documents: http://www.mybatis.org/generator/index.html
Introductory case
This document uses springboot combined with Mybatis-generator plugin, database MySQL.
New Project
Create a new Springboot project.
Dependent files
In the project Pom file, the Mybatis-generator plug-in is introduced, and the MyBatis and MySQL dependencies are introduced. The complete POM code is as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apache . org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.dalaoyang</ Groupid> <artifactId>springboot_generator</artifactId> <version>0.0.1-snapshot</version > <packaging>jar</packaging> <name>springboot_generator</name> <description>spri Ngboot_generator</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.15.RELEASE</version> <relativePath/> <!--lookup parent from repository to </parent> <properties> &L T;project.build.sourceencoding>utf-8</prOject.build.sourceencoding> <project.reporting.outputencoding>utf-8</ project.reporting.outputencoding> <java.version>1.8</java.version> </properties> <DEP Endencies> <dependency> <groupId>org.springframework.boot</groupId> < Artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependenc y> <dependency> <groupId>org.springframework.boot</groupId> <artifact id>spring-boot-starter-web</artifactid> </dependency> <dependency> <group Id>org.mybatis.spring.boot</groupid> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupi D>org.springframework.boot</groupid> ≪artifactid>spring-boot-devtools</artifactid> <scope>runtime</scope> </depende ncy> <dependency> <groupId>mysql</groupId> <artifactid>mysql-conne ctor-java</artifactid> <scope>runtime</scope> </dependency> </dependencies > <build> <plugins> <plugin> <groupid>org.mybatis.generator </groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <ver Sion>1.3.2</version> <executions> <execution> <id>mybatis-generator</id> <phase>deploy</phase> & Lt;goals> <goal>generate</goal> </goals> </execution&Gt </executions> <configuration> <!--the location of the Mybatis-generator tool configuration file-- <configurationfile>src/main/resources/mybatis-generator/generatorconfig.xml</configurationfile> ; <verbose>true</verbose> <overwrite>true</overwrite> </configu ration> <dependencies> <dependency> <groupid> ;mysql</groupid> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactid>mybatis -generator-core</artifactid> <version>1.3.2</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-maven-plug In</artifactid> <configuration> <classifier>exec</classifier> </configuration> </plugin> </plugins> </build></project>
Configuring the Mybatis-generator Configuration
Create a new generatorconfig.xml in the location of the Mybatis-generator tool configuration file configured in the Pom file (the location of this case configuration is src/main/resources/mybatis-generator/ Generatorconfig.xml), the configuration file code is as follows, the specific configuration needs to modify itself to its own project:
<?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 "><!--Configuration Generator--><generatorconfiguration> <!-- command to execute Generator plug-in makefile: Call MVN MYBATIS-GENERATOR:GENERATE-E-<!--Introducing configuration Files--<properties resource= "a Pplication.properties "/> <!--classpathentry: Database JDBC driver, switch to your own drive location optional-<!--<classpathentry Locatio n= "D:generator_mybatismysql-connector-java-5.1.24-bin.jar"/>-<!--a database one context--<!--default Modeltype= "flat" Big data field, no table--<context id= "Mysqltables" targetruntime= "Mybatis3simple" defaultmodeltype= "flat "> <!--automatically identify database keywords, default false, if set to true, based on the list of keywords defined in sqlreservedwords; generally keep default values, encounter database keywords (java keyword), use Columnov Erride Overlay--<property name= "Autodelimitkeywords" value= "true"/> <!--encoding of generated Java files --<property name= "javafileencoding" value= "Utf-8"/> <!--beginningdelimiter and Endingdelimiter: Indicates that the database is used to mark the names of database objects, such as Oracle is double quotes, mysql default is ' anti-quote; '--<property name= "Beginningdelimiter" value= ""/> <property name= "Endingdelimiter" value= "'"/> <!--formatted Java code--<property name= "Javaformat ter "value=" Org.mybatis.generator.api.dom.DefaultJavaFormatter "/> <!--formatted XML code--<property NA Me= "Xmlformatter" value= "Org.mybatis.generator.api.dom.DefaultXmlFormatter"/> <plugin type= " Org.mybatis.generator.plugins.SerializablePlugin "/> <plugin type=" Org.mybatis.generator.plugins.ToStringPlugin "/> <!--notes--<commentgenerator > & Lt;property name= "Suppressallcomments" value= "false"/><!--whether to uncomment--<property name= "Suppressdate" Value= "true"/> <!--generate comment generation timestamp-</commentGenerator> <!--JDBC Connection--<jdbcconnection driverclass= "${spring.datasource.driver-class-name}" connectionurl= "${sp Ring.datasource.url} "userid=" ${spring.datasource.username} "password=" ${spring.datasource.password} "/> <!- -Type conversion-<javaTypeResolver> <!--use BigDecimal, false to automatically convert the following types (Long, Integer, short, etc. )--<property name= "Forcebigdecimals" value= "false"/> </javaTypeResolver> <!- -Generate entity class address--<javamodelgenerator targetpackage= "com.dalaoyang.entity" targetproject= "${mybatis.project}" ; <property name= "Enablesubpackages" value= "false"/> <property name= "trimstrings" value= "true"/> </javaModelGenerator> <!--generate mapxml Files--<sqlmapgenerator targetpackage= "Mapper" TARGETPR oject= "${mybatis.resources}" > <property name= "enablesubpackages" value= "false"/> </SQLMAPG Enerator> <!--generate mapxml corresponding to the client, that is, the interface Dao--<javaclientgenerator targetpackage= "Com.dalaoyang.dao" TARGETPR oject= "${mybatis.project}" type= "Xmlmapper" > <property name= "enablesubpackages" value= "false"/> </javaClientGenerator> <!--table can have multiple tables in each database can write a table,tablename representing the database table to match, or you can use the% wildcard in the TableName property To match all database tables, only matching tables will automatically generate files--<table tablename= "user" enablecountbyexample= "true" enableupdatebyexample= "true" Enabledeletebyexample= "true" enableselectbyexample= "true" selectbyexamplequeryid= "true" > <property name= "Useactualcolumnnames" value= "false"/> <!--database table primary Key--<generatedkey column= "id" sqlsta Tement= "Mysql" identity= "true"/> </table> <table tablename= "book" enablecountbyexample= "true" E Nableupdatebyexample= "true" enabledeletebyexample= "true" enableselectbyexample= "true" selectbyexamplequeryid= " True "> <property naMe= "Useactualcolumnnames" value= "false"/> <!--database table primary Key--<generatedkey column= "id" sql Statement= "Mysql" identity= "true"/> </table> </context></generatorConfiguration>
Configure Application.properties
Configuration item application.properties, where the database information, mapper address before have been introduced, specific springboot-mybatis configuration can refer to:
"Springboot+mybatis+mysql Study"
This article is configured as follows:
## mapper xml 文件地址mybatis.mapper-locations=classpath*:mapper/*Mapper.xml##数据库urlspring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false##数据库用户名spring.datasource.username=root##数据库密码spring.datasource.password=123456##数据库驱动spring.datasource.driver-class-name=com.mysql.jdbc.Driver#Mybatis Generator configuration#dao类和实体类的位置mybatis.project =src/main/java#mapper文件的位置mybatis.resources=src/main/resources
In fact, the configuration is complete, you can experience the advantages of the Mybatis-generator plug-in, the right maven click on the location,
When you click Done, you can see the Mapper,dao, and the entity classes are all created.
Creating a completion will give me a few default build methods, such as the Usermapper code as follows:
Package Com.dalaoyang.dao;import Com.dalaoyang.entity.user;import Org.apache.ibatis.annotations.mapper;import Java.util.list;public interface Usermapper {/** * This method is generated by MyBatis Generator. * This method corresponds to the database table user * * @mbggenerated */int deletebyprimarykey (Long ID); /** * This method is generated by MyBatis Generator. * This method corresponds to the database table user * * @mbggenerated */int insert (user record); /** * This method is generated by MyBatis Generator. * This method corresponds to the database table user * * @mbggenerated */user Selectbyprimarykey (Long ID); /** * This method is generated by MyBatis Generator. * This method corresponds to the database table user * * @mbggenerated */list<user> SelectAll (); /** * This method is generated by MyBatis Generator. * This method corresponds to the databaseTable User * * @mbggenerated */int updatebyprimarykey (user record);}
The
Usermapper.xml code is as follows:
<?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.dalaoyang.dao.UserMapper" > <resultmap id= "baseresultmap" type= " Com.dalaoyang.entity.User "> <!--warning-@mbggenerated This element was automatically generated by My Batis Generator, do not modify. --<id column= "id" property= "id" jdbctype= "BIGINT"/> <result column= "user_name" property= "UserName" JD bctype= "varchar"/> <result column= "User_password" property= "UserPassword" jdbctype= "varchar"/> </result map> <delete id= "Deletebyprimarykey" parametertype= "Java.lang.Long" > <!--warning-@mbggenerated This element is a automatically generated by MyBatis Generator, does not modify. --delete from user where id = #{id,jdbctype=bigint} </delete> <insert id= "Insert" parametertype= "com . dalaoyang.entity. User > <!--warning-@mbggenerated This element was automatically generated by MyBatis Generator, do n OT modify. --<selectkey resulttype= "Java.lang.Long" keyproperty= "id" order= "after" > select last_insert_id () &l t;/selectkey> INSERT INTO User (user_name, User_password) VALUES (#{username,jdbctype=varchar}, #{userpassword,jd Bctype=varchar}) </insert> <update id= "Updatebyprimarykey" parametertype= "Com.dalaoyang.entity.User" > & lt;! --warning-@mbggenerated This element was automatically generated by MyBatis Generator, does not modify. --Update user set user_name = #{username,jdbctype=varchar}, User_password = #{userpassword,jdbctype=varcha R} WHERE id = #{id,jdbctype=bigint} </update> <select id= "Selectbyprimarykey" resultmap= "Baseresultmap" para Metertype= "Java.lang.Long" > <!--warning-@mbggenerated This element was automatically generated by My Batis GenerAtor, do not modify. --Select ID, user_name, user_password from user where id = #{id,jdbctype=bigint} </select> <selec T id= "SelectAll" resultmap= "Baseresultmap" > <!--warning-@mbggenerated This element is automatically Generated by MyBatis Generator, does not modify. --Select ID, user_name, user_password from user </select></mapper>
Testing using new test methods
adding annotations on Usermapper @mapper indicates that it is a persistent mapping layer, adding annotations @restcontroller on the start class to test, here simply call a query all methods SelectAll, the startup class code is as follows:
@SpringBootApplication@RestControllerpublic class SpringbootGeneratorApplication { @Autowired private UserMapper userMapper; @GetMapping("/findAll") public List<User> findAll(){ return userMapper.selectAll(); } public static void main(String[] args) { SpringApplication.run(SpringbootGeneratorApplication.class, args); }}
Run Tests
To run the project, the browser accesses Localhost:8080/findall:
SOURCE download: Big old Yang Code cloud
Springboot using Mybatis-generator