About MyBatis Generator
MyBatis Generator (MBG) is a MyBatis code generator MyBatis and IBATIS. He can generate MyBatis versions of the code, and Ibatis 2.2.0 version of the code after. He can introspect the tables (or tables) of the database and generate the underlying objects that can be used to access (multiple) tables. This does not require the creation of objects and configuration files when interacting with database tables. MBG solves a number of simple crud (insert, query, UPDATE, DELETE) operations that have the greatest impact on database operations. You still need to write SQL and objects for federated queries and stored procedures.
MyBatis Generator will generate:
The Java POJO that match the table structure may include:
- A class that matches the primary key of the table (if there is a primary key [note: Only the joint primary key will be available])
- A class that contains a field that is not a primary key (except for a BLOB field [Note: This will be included when the Word field is the master key])
- A class that contains a BLOB field (if the table contains a BLOB field)
- A class that allows dynamic query, update, and delete [note: Refers to the example query]
There is an appropriate inheritance relationship between these classes. Note that you can configure the builder to generate different types of POJO hierarchies. For example, if you prefer, you might choose to generate a separate entity object for each table.
Mybatis/ibatis compatible SQL map XML file. MBG generates SQL for a simple CRUD operation for each table in the configuration. The resulting SQL statements include:
- Insert (INSERT)
- Update by primary key (update records based on primary key)
- Update by example (Update records based on criteria)
- Delete by primary key (delete records based on primary key)
- Delete by example (delete records according to criteria)
- Select by primary key (query records based on primary key)
- Select by example (query recordsets based on criteria)
- Count by example (total number of records queried based on criteria)
Depending on the structure of the table, the resulting statements will vary (for example, if the table does not have a primary key, then MBG will not generate the update by primary key method).
The Java client class uses the above object appropriately, and optionally generates Java client classes. MBG will generate the following client classes for MyBatis 3.x:
A mapper interface class that can be used with MyBatis 3.x
MBG will generate the following client classes for Ibatis 2.x:
A DAO class that conforms to the Spring framework.
DAO that uses only the Ibatis SQL mapping API. This DAO can be generated in the following two ways: providing sqlmapclient by means of construction or setter injection.
Ibatis DAO framework-compliant DAO (Ibatis optional part, this framework is obsolete and we recommend that you use the Spring framework instead).
MyBatis generator can run well in an iterative development environment as an ant task or Maven plug-in in an ongoing build environment. The following important things to keep in mind when running MBG:
MBG automatically merges XML that already exists and has the same name as the newly generated file. MBG does not overwrite the modifications you have made to the XML you have generated. You can run it repeatedly without worrying about losing your customized changes. MBG will replace all the XML elements that were generated in the previous run.
MBG does not merge Java files, he can overwrite existing files or save newly generated files as a different unique name. You can merge these changes manually. When you use the Eclipse plug-in, MBG can automatically merge the Java files.
Basic usage
MBG's operation relies mainly on an XML configuration file, first we can re-create a new project named Mybatisgenerator, new 3 packages named Config, David.test, and David.mbg,config package mainly store the real mybatis inside need to use the configuration file, you can put the previous chapters in the project Mybatis_demo_ Config.xml copy to put in this directory, and so on as a test program, David.test, as the name implies is to store the following commonly used methods and test procedures you can also bar in the first few chapters used to Mybatisutils tools to take over, new good mainfunction for testing purposes. And the final DAVID.MBG is the XML,MBG build configuration file that we're going to configure today.
As shown in the figure, we create a new configuration file named Mbg_configuration.xml below, as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis generator Configuration" "1.0//en 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 notes--> <commentGenerator> <!--whether to remove all automatically generated annotation files--> <property name= "su Ppressallcomments "value= true"/> <!--Remove all automatically generated file timestamps, default to False--> <property name= "Suppressdat E "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> <!--converts the decimal and numberic types in JDBC to the integer type--> ≪property name= "Forcebigdecimals" value= "false"/> </javaTypeResolver> <!--database table corresponding to model--> <javamodelgenerator targetpackage= "David.model" targetproject= "src" > <property name= "EnableSubPackage" S "value=" true "/> <property name=" trimstrings "value=" true "/> </javaModelGenerator> <!-- Control model Xmlmapper File--> <sqlmapgenerator targetpackage= "david.mappers" targetproject= "src" > < Property Name= "Enablesubpackages" value= "true"/> </sqlMapGenerator> <!--control Mapper interface--> <ja Vaclientgenerator targetpackage= "David.inter" type= "xmlmapper" targetproject= "src" > <property name= "Enab" Lesubpackages "value=" true "/> <property name=" Methodnamecalculator "value=" extended "/> </javaclien Tgenerator> <!--schema your database, tablename indicates that domainobjectname corresponds to your JavaBean class name, whether to generate the corresponding example--> <table Ma= "mybatis_db" TablenamE= "Visitor" domainobjectname= "visitor" enablecountbyexample= "false" enableupdatebyexample= "false" Enabledelete Byexample= "false" enableselectbyexample= "false" Selectbyexamplequeryid= "false" > <generatedkey column= "id "Sqlstatement=" MySql/> <columnoverride column= "name" property= "Visitor_name"/> <ignorecolumn C olumn= "status" Delimitedcolumnname= "false"/> </table> </context> </GENERATORCONFIGURATION&G
T
You can note that the main ones are actually these nodes
<classPathEntry>=> location of the JDBC driver package, either relative or absolute, the relative path is used in the example
<context>=> corresponds to the configuration of all tables under a database, there can be multiple context, one configuration MySQL, one configuration Oracle.
The main <context> nodes are:
<commentGenerator> => Annotation Generation node, the 2 sub nodes in this example are represented
Suppressallcomments => whether to remove all automatically generated annotation files
Suppressdate => whether to remove the timestamp of all automatically generated files, default to False
<jdbcConnection> => Database Connection configuration information
<javaTypeResolver> => converts the decimal and numberic types in JDBC into Java.math.BigDeciaml representations
<javaModelGenerator> => Configuration of your Pojo entity class, targetpackage= "David.model", corresponding to your registration, you can own according to the actual business name, targetproject= "src" , in the eclipse environment, refers to the project and source folder path generally refers to the SRC directory, your package will be new in this directory, if not the eclipse environment, the value here should be a real file system path, if the specified path does not exist will be an error, Because MBG does not create the appropriate folder on its own
<sqlMapGenerator> => configuration generates the corresponding entity Mapper.xml, for mapper3.x we need to type= "Xmlmapper"
<javaClientGenerator> => configuration generates corresponding interface classes, corresponding to a series of CRUD method SQL statements in Mapper.xml
<table> => Configure the corresponding database to indicate that you want to generate the domain class name (that is, the entity class name), in this example I have closed all unnecessary example generation information
All of the above information can go to the official website to check the corresponding documents, or to my files to download, the corresponding configuration instructions and related application examples. Downloading documents
After configuring the information above, what is the last step, we are going to run this script file, the official description in 4 ways, first through the command-line, second, Sandu through the tools such as Ant or Maven, the last one is generated through Java code, We're going to use the Java Barley Generation method here. Add a script-generating method to the Demorun class as follows:
private static void Generatembgconfiguration () {/* * MyBatis the 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 ("Build mybatis configuration succeeded!")
");
}
After running and then refresh under the item you will find the following magic to help you generate the main configuration, the following Figure Red Box section:
Finally, let's use the results of the automatic generation, we can refer to the first six chapters in the way, add the corresponding Crud test method in Demorun is 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 ("helloworld2@qq.com");
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.getsqlse
Ssion ();
Visitormapper voperation = Session.getmapper (Visitormapper.class);
Visitor Visitor = Voperation.selectbyprimarykey (ID);
Mybatisutils.closesession (session);
Mybatisutils.showmessages (Crud_enum.query, 1);
System.out.println (visitor); The 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 results come out.
There's no sense in using this to help you improve your efficiency, need not be in for cumbersome configuration and headache, at least do not repeat unnecessary steps, let these all to the tool to do it ^0^, of course, in the actual use we may need to modify the corresponding class information and interface information name after the generation, Of course, these workloads are not too much. I hope today's content is helpful to the students who need to be configured.