Write what you thought after using mybatis for half a year
What is mybatis?
- https://github.com/mybatis/mybatis-3
It is a kind of OR mapper for Java and has the following features.
- Write SQL in annotation or xml file
- Easy to apply to non-normalized legacy systems
- Easy to tune SQL, so it is easy to apply to systems where DB tends to be a performance bottleneck.
It's been half a year since I used it in the project I'm in charge of, so I'll write down the good points and issues.
good point
The class used for SQL access is reduced
For JDBC
- As a promise, use the following classes
- DataSource
- Connection
- PreparedStatement
- ResultSet
- You need to remember to close Coneection, PreparedStatement, and ResultSet when the SQL issuance process is finished.
For mybatis
- The following two libraries are used for SQL access
- SqlSessionFactory
- SqlSession
- Only SqlSession can be closed
- Of course, you don't need to getValue () from ResultSet and set it to the object.
Can write SQL in XML
When assembling SQL in Java
StringBuffer sql = new StringBuffer();
sql.append("select * from table ");
sql.append("where id=? ");
sql.toString();
- With this, sometimes I want to extract only SQL and execute it from Workbench or pgAdmin, which is very annoying.
For Mybatis Mapper XML
<select id="selectPerson" parameterType="int" resultType="hashmap">
SELECT * FROM PERSON WHERE ID = #{id}
</select>
- Since it can be written as the contents of the XML tag element, it is much easier to cut out only here and execute it for a while.
SQL is completely separated from logic (Java file)
- Therefore, it is easy to count the number of SQL and logic steps separately.
- In our product, SQL has as many steps as logic! DB ghost system! You can do self-deprecation
Bad point
Since it is XML, the refactoring function of eclipse cannot be used.
- When you want to rename the Model class, you need to grep the source ... and do something like a scripting language.
Since it is XML, coverage cannot be obtained.
- In my project, I use Jacoco to measure coverage, but of course I can't measure coverage in a Mapper XML file.
- In XML, you can write an if statement that adds a where clause only when a value is specified, but I don't know if it covers all of this.
Summary
- I don't have much insight, but I'm generally happy with mybatis
- Why not consider it when maintaining a legacy app?