About Mybatis Generator
MyBatis Generator (MBG) is a Mybatis code generator MyBatis and iBATIS. It can generate code for various versions of Mybatis, and code after iBATIS 2.2.0. He can introspect the tables (or tables) of the database and then generate the underlying object that can be used to access the tables (multiple) of the tables. This way, no objects and configuration files are required when interacting with database tables. MBG solves some simple CRUD (insert, query, update, delete) operations that have the greatest impact on database operations. You still need to handwritten SQL and objects on the federation query and stored procedures.
MyBatis Generator will generate:
Java POJOs matching table structures may include:
There will be an appropriate inheritance relationship between these classes. Note that the generator can be configured to generate hierarchies of different types of POJOs. For example, if you prefer you might choose to generate a separate entity object for each table.
MyBatis/iBATIS compatible with SQL-mapping XML files. MBG generates SQL in configuration for simple CRUD operations for each table. The generated SQL statements include:
Depending on the table's structure, the generated statements will vary (for example, if there is no primary key in the table, then MBG will not generate the update by primary key method).
The Java client class will use the above object appropriately, and is optional when generating the Java client class. MBG will generate the following client class for MyBatis 3.x:
A mapper interface class that can be used with MyBatis 3.x
MBG will generate the following client class for iBATIS 2.x:
DAO class that complies with Spring framework.
Use only the DAO of the iBATIS SQL mapping API. This DAO can be generated in the following two ways: provide SqlMapClient through construction methods or setter injection.
DAO compliant with the iBATIS DAO framework (an optional part of iBATIS, which is outdated, we recommend that you use Spring framework instead).
MyBatis generator can run well in an iterative development environment and act as an ant task or maven plug-in in a continuous build environment. The following important things to remember when running MBG:
MBG will automatically merge XML that already exists and is duplicated with the newly generated file. MBG does not overwrite the modifications you made to the XML you have generated. You can run it over and over without worrying about losing your custom changes. MBG will replace all XML elements generated in previous runs.
MBG does not merge Java files, it can overwrite existing files or save newly generated files to a different unique name. You can merge these changes manually. When you use the Eclipse plugin, MBG can automatically merge Java files.
Basic usage
MBG mainly relies on an XML configuration file. First, we can re-create a new project named MybatisGenerator, create three new packages named config, david.test, and david.mbg. The config package mainly stores the configuration files needed in real Mybatis. You can copy the mybatis_demo_config.xml from the project in the previous chapters and put it in this directory, etc. for testing programs. As the name implies, david.test is to store the following commonly used methods and test programs. You can also use the MybatisUtils tool class in the previous chapters and create the corresponding MainFunction for testing purposes. And the last david.mbg is the XML we are going to configure today and the MBG generates configuration file.
As shown in the figure, we have created a new configuration file called mbg_configuration.xml below. The details are as follows:
<?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="./lib/mysql-connector-java-5.1.26-bin.jar" /> <context id="mybatisDemoForMysql" targetRuntime="MyBatis3"> <!-- Control comments--> <commentGenerator> <!-- Whether to remove all automatically generated comment files--> <property name="suppressAllComments" value="true" /> <!-- Whether to remove the timestamps of all automatically generated files, default to false --> <property name="suppressDate" value="true" /> </commentGenerator> <!-- Control database--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis_db?characterEncoding=utf8" userId="root" password="david0110" /> <javaTypeResolver> <!-- Convert decimal and number types in jdbc into integer types--> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- Model corresponding to database table --> <javaModelGenerator targetPackage="david.model" targetProject="src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- Control the Model's xmlMapper file--> <sqlMapGenerator targetPackage="david.mappers" targetProject="src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- Control the mapper interface--> <javaClientGenerator targetPackage="david.inter" type="XMLMAPPER" targetProject="src"> <property name="enableSubPackages" value="true" /> <property name="methodNameCalculator" value="extended" /> </javaClientGenerator> <!-- schema for your database, tableName indicates that the domainObjectName corresponds to your javabean class name, whether the corresponding example is generated --> <table schema="mybatis_db" tableName="visitor" domainObjectName="Visitor" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <generatedKey column="id" sqlStatement="MySql" /> <columnOverride column="name" property="visitor_name" /> <ignoreColumn column="status" delimitedColumnName="false" /> </table> </context></generatorConfiguration>
You can notice that it is mainly these nodes
<classPathEntry>=> The location where the jdbc driver package is stored can be used to use relative paths or absolute paths. In this example, the relative path is used.
<context>=>Complied with the configuration of all tables in a database, there can be multiple contexts, one configuration mysql and one configuration oracle.
The main ones under the <context> node are:
<commentGenerator> => Comment Generator nodes, the 2 sub-tables in this example represent
suppressAllComments => Whether to remove all automatically generated comment files
suppressDate => Whether to remove the timestamps of all automatically generated files, default to false
<jdbcConnection> => Database connection configuration information
<javaTypeResolver> => Convert decimal and number types in jdbc into java.math.BigDeciaml form representation
<javaModelGenerator> => Configure your POJO entity class, targetPackage="david.model", corresponding to your registration, you can name it according to the actual business, targetProject="src". In the Eclipse environment, the path to the project and source folder is generally referred to as the src directory. Your package will be newly created in this directory. If it is not the Eclipse environment, the value here should be an actual file system path. If the specified path does not exist, an error will be reported, because MBG will not create the corresponding folder by itself
<sqlMapGenerator> => Configure to generate the corresponding entity Mapper.xml. For Mapper3.X, we need to type="XMLMAPPER"
<javaClientGenerator> => Configure generates the corresponding interface class, corresponding to a series of CRUD method SQL statements in Mapper.xml
<table> => Configure the corresponding database, which indicates that the domain class name (that is, entity class name) is wanted to generate. In this example, I closed all unnecessary example generation information
All the above information can be checked on the official website for the corresponding documents, or downloaded in my file, with the corresponding configuration instructions and related application examples. Download the document
After configuring the above information, what is the last step? We are going to run this script file. There are 4 ways in the official description. The first is through the command line method, the second and third are generated through tools such as Ant or Maven. The last one is generated through Java code. We use the method of generating through Java barley. The method of adding a generated script to the DemoRun class is as follows:
private static void generateMbgConfiguration() { /* * Mybatis comes with Generator tool to generate the corresponding thing*/ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("./src/david/mbg/mbg_configuration.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = null; try { config = cp.parseConfiguration(configFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } DefaultShellCallback callback = new DefaultShellCallback(overwrite); try { MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("The Mybatis configuration was generated successfully! "); } After running, Refresh the project, you will find that the following magically generates the main configuration for you. The red box section of the figure below:
Finally, let’s use the automatically generated results. We can refer to the first six chapters to add the corresponding CRUD test method to DemoRun as follows:
/* * Query visitor information*/ public static void testGenerateAdd() { SqlSession session = MybatisUtils.getSqlSession(); VisitorMapper vOperation = session.getMapper(VisitorMapper.class); Visitor visitor = new Visitor(); visitor.setVisitor_name("hello2"); visitor.setEmail("[email protected]"); visitor.setCreatetime(new Date()); int count = vOperation.insert(visitor); session.commit(); MybatisUtils.closeSession(session); MybatisUtils.showMessages(CRUD_Enum.Add, count); } /* * Query visitor information*/ public static void testGenerateQuery(int id) { SqlSession session = MybatisUtils.getSqlSession(); VisitorMapper vOperation = session.getMapper(VisitorMapper.class); Visitor visitor = vOperation.selectByPrimaryKey(id); MybatisUtils.closeSession(session); MybatisUtils.showMessages(CRUD_Enum.Query, 1); System.out.println(visitor); } public static void testGenerateDelete(int id) { SqlSession session = MybatisUtils.getSqlSession(); VisitorMapper vOperation = session.getMapper(VisitorMapper.class); int count = vOperation.deleteByPrimaryKey(id); session.commit(); MybatisUtils.closeSession(session); MybatisUtils.showMessages(CRUD_Enum.Delete, count); } public static void testGenerateUpdate(int id) { SqlSession session = MybatisUtils.getSqlSession(); VisitorMapper vOperation = session.getMapper(VisitorMapper.class); Visitor visitor = vOperation.selectByPrimaryKey(id); System.out.println(visitor); String name = visitor.getVisitor_name(); if (name.contains("update")) { visitor.setVisitor_name(name.substring(0, name.indexOf("update"))); } else { visitor.setVisitor_name(name + "update"); } int count = vOperation.updateByPrimaryKey(visitor); session.commit(); MybatisUtils.closeSession(session); MybatisUtils.showMessages(CRUD_Enum.Update, count); System.out.println(visitor); } Run the test program and the result is
Do you feel that using this has helped you improve your efficiency a lot, and you don’t have to worry about cumbersome configurations. At least you don’t have to do repetitive and unnecessary steps. Let these be left to the tools to do^0^. Of course, in actual use, we may need to modify the corresponding class information and interface information names after generation. Of course, these workloads are not too much. I hope these contents will be helpful to students who need to configure them today.