How can the code for dao and entity be generated automatically in actual development?A tool for you

Keywords: Java Database Mybatis MySQL

01

Focusing on your "Ape Story" friends, you know that previous articles have advocated rejection of CRUD. What is CRUD?Today let's talk about how the Java sisters and apes interact with the old database man.

 

Product Xiao Wang Tiao said forcefully: Ape classmates, let's launch a pop-up product in the near future, you first achieve the user's basic login function.

 

What?Ape murmurs: Explosive products and basic login, isn't that CRUD for users?

 

In a word, Xiao Wang exhausted the three armed forces.At the end of the morning chatting session, the ape called for a takeout, filled the empty stomach, and the ape habitually began to build a brain map of the explosive products from 0 to 1.

 

 

The idea of the ape is to first analyze the requirements of the product to see if there are any missing demand function points, then design the database table structure, and then the code operation that the ape likes.

 

The way the ape code is coded, which is notoriously very serious, draws everyone's attention.

 

Previously, it was just hearsay that what you see today is a real story.First the ape worked hard on sqlmaps, writing mapping files with letters and punctuation; then one entity class was defined, and the fields of the database table were mapped one by one; then the dao code was written in the same careful way; and finally, he went back to confirm that the fields of the database table correspond to the entity class one by one.

 

Looking at the ape's serious attitude is really commendable.But after looking around the ape code, I see that I have kidney pain instead. Isn't that all repetitive work? Isn't there any good way to recommend it to apes?

 

02

 

With the ape's free-hand tools.

 

Ape, you find your favorite directory and create a folder. You name it mybatis-generator. It doesn't matter what the name is. This is your toolkit directory. Everything below is in this directory.

 

Ape, check to see if there are any driver packages connected to the database on your computer. If we don't download one, give you a download link, and give you another minute to download the jar package. I'll use it later. I'll smoke a cigarette.

https://repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Ape, have you downloaded it yet? I've finished smoking a cigarette.

 

Now that you've downloaded it, check to see if you have this package mybatis-generator-core-1.3.2.jar on your computer. Whatever it is for, just download it at the address below. It will be used later anyway.

https://repo1.maven.org/maven2/org/mybatis/generator/mybatis-generator-core/1.3.2/mybatis-generator-core-1.3.2.jar

  

Ape, we're almost ready now, but you need to create a configuration file, generatorConfig.xml. Don't worry about the contents of the file, just take the code below and change it.Be sure to change all the directories involved to those on your computer. First you modify them for a while. I'll make a cup of coffee and have a drink.The contents are as follows (be careful to modify the directory)

<?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>
  <!-- Specify Data Connection Driver jar address -->
  <classPathEntry
    location="/app/mybatis-generator/mysql-connector-java-5.1.38.jar" />

  <!-- Specify Data Connection Driver jar address -->
  <context id="db2Tables" targetRuntime="MyBatis3">
    <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
    <commentGenerator>
      <property name="javaFileEncoding" value="UTF-8"/>
      <!-- Whether to generate comment generation timestamps -->
      <property name="suppressDate" value="true" />
      <!-- Whether to uncomment -->
      <property name="suppressAllComments" value="false" />
    </commentGenerator>

    <!--Information for database connection: driver class, connection address, user name, password -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
      connectionURL="jdbc:mysql://localhost:3306/baokuan"
      userId="root" password="root" />

    <!-- targetProject: Generate directories for entity classes -->
    <javaModelGenerator targetPackage="com.cool.baokuan.modules.model"
      targetProject="/app/mybatis-generator/src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!-- targetProject: mapper Mapping File Generation Location -->
    <sqlMapGenerator targetPackage="com.cool.baokuan.modules.dao"
      targetProject="/app/mybatis-generator/src">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- targetPackage: mapper Location of interface generation -->
    <javaClientGenerator targetPackage="com.cool.baokuan.modules.dao"
      targetProject="/app/mybatis-generator/src" type="XMLMAPPER">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- Specify database tables -->
    <table tableName="T_USER" domainObjectName="User"
      enableCountByExample="false" enableUpdateByExample="false"
      enableDeleteByExample="false" enableSelectByExample="false"
      selectByExampleQueryId="false"/>
      
  </context>
</generatorConfiguration>

  

Ape, have you finished changing the catalog?

 

Now that you've finished, that's the last step. You're creating an execution script. Your system is Windows, so the script name is run.bat, and my Mac is Mac, so my script name is run.sh.copy the following when the creation is complete.

Java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite

  

Okay, ape, congratulations on building the toolkit by hand. Would you like to see the result for yourself?

 

 

Ape, mule is a horse. Let's all take it out and slip away.It's time for your little knife to try and sing.Try running.bat or run.sh with one click.

 

 

Wow, the ape is stunned to see the above effect, because with this tool, you can no longer duplicate mapping files, entity classes, dao, but configure the table name of the database. It's just handsome.

 

Ape, don't be overjoyed.When you use this tool in the future, be sure to modify the following places in the generatorConfig.xml file, or the moths will come out.

1. Modify the specified data connection driver jar address;	
2. Modify the url, user name and password of the database connection;	
3. Modify the targetProject directory to be the directory of your computer;	
4. Modify database tables.

  

Okay, ape, master takes it into the ape door. The practice is personal. You will see your own creations later.

 

03

 

The ape is busy trying to trick people.

 

Just a few days after the product came online, the number of users has increased sharply. It is a real explosive product. User queries are getting slower and slower.

 

The product Wang Niu was forced to say: Ape, there are a lot of user response system experience slower and slower recently, is there a Bug in the code?

 

What's wrong? There are bugs in the code. How can there be bugs in the code?In fact, the inside of the ape is just like a mirror. It is clearer than anyone else that the user table is too big to query too slowly. What should we do?

 

See the ape, take out the magic pen, rewrite the "database table" in this book, and then start a series of brainstorming checking process of the database table, have to admire the ape's mathematical proficiency, while the ape is not aware, I secretly remember some, and quickly share it with you.

 

Rules for Base Subtables

 

If there are M database master nodes, the data table is totally split into N sub-tables, and the split table field can be numerically converted to X, the database instance's ordinal number is X% M; the data table's ordinal number is X% N.

 

For example, when the number of primary nodes M=6 and the total number of split tables N=1200, the number of subtables in a single library is 200, the sequence number of the database instance is X% 6, and the sequence number of the data table is X% 1200.

 

So in a database with a sequence number of 0, there will be a sequence number of 0,6,12,18...A table; in a database with a sequence number of 1, there will be a sequence number of 1,7,13,19...Data tables, and so on.

 

Numerization Mechanism for Split Table Fields

 

Tables are split according to the field, crc32 is taken, and then the absolute value is taken, which is the X in the above "Repository Subtable Formula".

 

Unexpectedly, the ape wrote a pseudocode for it.

java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();	
// Split field for crc32	
crc32.update(splitField.getBytes(DEFAULT_ENCODING));	
long x = java.lang.Math.abs(crc32.getValue());	

	
// Database Subscript	
long n = x % dbNum;	
String dbPos = String.format("%02d", n);	
System.out.println("Subscript of database:" + dbPos);	

	
// Table Subscript	
long m = x % tableNum;	
String tablePos = String.format("%03d", m);	
System.out.println("Table subscripts:" + tablePos);

  

Moreover, the ape wrote three times at the end of the draft: Sharing-Jdbc, Sharing-Jdbc, Sharing-Jdbc.Especially three times, so each of you will have to brainstorm for this, or you will never be able to keep up with the ape in the future.

 

04

It's a little ape that you can watch together, and when you see it, I can only worship the ape by ORZ.Quote a classic: Your grandfather is still your grandfather, but the ape is no longer the ape that used to repeat CRUD.Don't look down on every ape around you because you're going to be impressed with them for three days.

 

 

Posted by Vebut on Sat, 04 Apr 2020 22:52:17 -0700