Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MyBatis or JPA?


May 31, 2021 Article blog


Table of contents


For a programmer dealing with a database, it can quickly be a difficult choice. Do you want to choose MyBatis or JPA

A lot of people say that technology choices have to be based on demand, and that's right. B ut, in addition to the demand, there is also a very important link, that is the level of teammates. If you choose some more advanced techniques, you're burying a hole in the team.

JPA is more abstract and the code is simpler to write, but it's not simple at all. Despite many trainings, several of the teams I've stayed with still use it like.

I threw away the JPA

I thought about it for a few reasons, which resulted in JPA not being able to play on many teams at all.

  1. JPA is suitable for business model fixed scenarios, suitable for more stable needs. B ut the domestic demand style, product manager this microphone-style design model, resulting in the flood of demand and uncertainty. JPA is scum in this mode.
  2. THE TECHNICAL REQUIREMENTS OF JPA ARE RELATIVELY HIGH. D on't doubt it, it may feel very simple when you're just starting to use it. B ut as you use it in depth, you'll find it a disaster. T he various transformations and caches inside will make people faint. And most fast food programmers don't want to know that.
  3. A lot of programmers are very good at writing SQL, so a lot of SQL statements are fat and long. B usiness chaos, multiple table associations, I've even seen hundreds of business tables associated with complex business. D BA helpless, usually there will be sql audit. J PA doing sql audits? It's still a little weaker.

So, it's not that JPA is bad, it's that it's not in line with the national conditions. To implement JPA within the company, you need to give me a stable product team, a Cow X technical team.

So it's logical that most companies would rather write a bunch of repetitive, messy MyBatis code than try JPA easily.

So, let's discuss MyBatis in the following article, and let's see how MyBatis actually writes to be elegant.

Why doesn't MyBatis work?

Good programmers are lazy. S o a lot of people don't want to design the sql of the entity. JPA can generate a library table of sql directly from Java's solid code, which is enviable to those who use MyBatis.

With MyBatis, it's going to be upside down. You need to design the library table first, and then reverse-generate a bunch of Java code and profiles based on the library table.

This code generator is mybatis-generator

However, please note. T here are 四种 modes of code generated by this generator!!! T his is what makes beginners most uncomfortable. If you're also new to MyBatis, it's highly recommended to focus only on the first mode below.

  • The MyBatis3 pattern is a common way to generate domain classes, Example classes, mapper mapping files, and so on. T he information it generates is so long that the content is almost unalterable. For self-written sql in a project, it is generally handwritten to write another copy, rather than changing the original file.
  • The simple code generation pattern of this pattern above MyBatis3Simple is missing something, but it's simple. There is no experience with MyBatis and it is not recommended.
  • MyBatis3DynamicSql This is a dynamic SQL feature implemented through TheBuilder mode and you will need to add additional jar packages. P lus it, it's actually a bit like JPA. I n that case, why not use JPA directly? So while this DSQL is the default build behavior, it is highly imperce recommended.
  • MyBatis3 Kotlin this is no nonsense. is to generate some configuration and code information for the Kotlin version.

So, here's just the code generation for MyBatis3 pattern.

To use it, you need to add its dependency to the pom .xml.



    org.mybatis.generator
    mybatis-generator-core
    true
    test
    1.4.0

Personally, I like to use Java code to manipulate the code generation process, so here's the code that generates the code.

public class MBGTool {
    public static void main(String[] args) throws Exception {
        List warnings = new ArrayList();
        boolean overwrite = true;
        InputStream configFile = MBGTool.class.getResourceAsStream("/generator/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

From the code, we can see that a generatorConfig.xml file needs to be configured to dictate how the code file is generated.






    

        

        

            

            

        

        

        

            

        
        <table tableName="test"/>

    

Once you've run our MBGTool file, you're ready to build MyBatis's code.

How to write code is the most elegant

However, I'm not recommending this pattern here. B ecause it generates a lot of useless files. If your project uses a code quality review tool like sonar, you'll find a lot of red-hot places, and that deadly coverage problem.

What to do?

After years of groping, I now recommend a very good way to write. I haven't changed since I adopted this method.

First, you don't need a code generator

The design of the data sheet, as well as the writing of the domain, all by hand. S o our code, if necessary, can also be migrated to JPA. T his pattern also learns by the way how the data types in Java correspond to the data types in SQL. When designing a watch, you can learn some of the principles behind it.

Second, you don't need to write a mapping file

What the generator generates is really a bunch of useless logic. For example, one of my data sheets doesn't need to provide query all and delete this action at all, it's still provided by default.

In this minimalist mode, we write the Mapper file directly and then declare only the required interface methods.

@Mapper
public interface AccountBasicMapper {
    @Insert("AccountBasicMapper/insert.sql")
    void insert(@Param("r") AccountBasic record);
}

As you can see, there's an Insert annotation, we've passed in a specific domain, and then we can write a specific sql statement in insert.sql file in the AccountBasicMapper directory.

Sql statements are like this:

INSERT INTO account_basic(
    account_id,
    nick_name,
    password,
    sex,
    state,
    photo_url,
    created,
    modified,
    version
)VALUES (
    ,
    ,
    ,
    ,
    ,
    ,
    ,
    ,

    
)

So what kind of grammar is this? H ow does it know it's configured like this? T his requires the introduction of MyBatis's scripting language configuration capabilities. Here we use the freemark template.

Don't forget to add to its dependence.



    org.mybatis.scripting
    mybatis-freemarker
    1.2.2

Then, in the yaml file to do the appropriate configuration ok.

mybatis:
  check_config_location: false
  scripting-language-driver:
    freemarker:
      template-file:
        base-dir: mappers/
      path-provider:
        includes-package-path: false
        separate-directory-per-mapper: false

The advantages and disadvantages of this approach

Personally, I like this model very much. Because it has several benefits:

  1. What to write, less code, simple and elegant.
  2. SQL set, not scattered in code, xml, or annotated. C onvenient for DBAs to conduct SQL audits. Without xml interference, SQL is more concise.
  3. A DAO method a sql file, the pattern is single and controllable.
  4. MyBatis's functional benefits are fully realized and seamlessly integrated.

Of course, the disadvantages are obvious.

  1. Even if you change a parameter, you have to modify a lot of sql files.
  2. Each method needs to be accompanied by a sql file, even if it is a very retarded insert query method.

However, I do not think this is a problem. E ach method is equipped with a sql file, and the code is easier to write. W hen something goes wrong, you also don't have to follow the logic to locate the stitched SQL statement. N ow, just need to get the corresponding method of SQL file, you can change it, directly in the sql terminal to perform debugging. In this way, sql optimization becomes simpler.

Of course, a person a habit. P ersonally, I like this model, and I've implemented it on my team and found it to work well. In addition, programmers have taken the Dao interface more seriously when designing it in order to write less repetitive sql code.

This may be an added bonus.

The article comes from the public name: Ape Logic, author Little Q

That's W3Cschool编程狮 About MyBatis or JPA? Finally, there's an answer! Related to the introduction, I hope to help you.