The difference between MyBatis and JDBC

Source: Internet
Author: User
Tags connection pooling


1. What is MyBatis?


MyBatis is an open source project for Apache Ibatis, which was migrated to Google code by the Apache Software Foundation in 2010 and renamed MyBatis. Migrated to GitHub in November 2013.



The term ibatis is derived from the combination of "Internet" and "Abatis" and is a Java-based persistence layer framework. Ibatis provides a durable layer framework that includes SQL maps and Data Access Objects (DAO).



MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of the result set. MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plain ordinary Java Objects, plain Java objects) to records in a database.





Back to top 2, why would there be MyBatis?


Through the above introduction, we know that MyBatis is to deal with the database. Well, before that, we were using JDBC to make a series of operations such as pruning and checking the database, and why would we give up using JDBC instead of using the MyBatis framework? Or what are the benefits of using MyBatis to compare JDBC?



Let's take a look at a JDBC action on the person table.



The person table is:



public class Person {
    private Long pid;
    private String pname;
    public Long getPid() {
        return pid;
    }
    public void setPid(Long pid) {
        this.pid = pid;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
}

JDBC Query Operation:


package com.ys.dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.DebugGraphics;
 
import com.ys.bean.Person;
 
public class CRUDDao {
    //MySQL database driver
    public static String driverClass = "com.mysql.jdbc.Driver";
    //MySQL username
    public static String userName = "root";
    //MySQL password
    public static String passWord = "root";
    //MySQL URL
    public static String url = "jdbc:mysql://localhost:3306/test";
    //Define database connection
    public static Connection conn = null;
    //Define statement database statement, use pre-compiled statement PreparedStatement to improve database execution performance
    public static PreparedStatement ps = null;
    //Define the return result set
    public static ResultSet rs = null;
    /**
     * Query person table information
     * @return: return the list collection of person
     */
    public static List<Person> readPerson(){
        List<Person> list = new ArrayList<>();
        try {
            //Load the database driver
            Class.forName(driverClass);
            //Get database connection
            conn = DriverManager.getConnection(url, userName, passWord);
            //Define sql statement,? Means placeholder
            String sql = "select * from person where pname=?";
            //Get the precompiled statement
            ps = conn.prepareStatement(sql);
            //Set the parameters in the sql statement, the first is the parameter in the sql statement? (starting from 1), the second is the parameter value set
            ps.setString(1, "qzy");
            //Send sql statement query to the database and return the result set
            rs = ps.executeQuery();
            while (rs.next()) {
                Person p = new Person();
                p.setPid(rs.getLong(1));
                p.setPname(rs.getString(2));
                list.add(p);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //Close the database connection
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
         
        return list;
    }
 
    public static void main(String[] args) {
        System.out.println(CRUDDao.readPerson());
    }
}



Back to top 3, analysis


From the above example we can analyze the following points:



①, problem One: Database connection, the use of the creation, the use of closed, so that the database will be frequently access to connect and close the connection, resulting in a waste of database resources, affecting database performance.



Scenario Resolution: Use database connection pooling to manage database connections



②, problem two: Hard code SQL statements into the program, if the SQL statement modified, then need to recompile Java code, not conducive to system maintenance



Imagine resolving: Configuring SQL statements into XML files, even if the SQL statements change, we do not need to modify the Java code, recompile



③, problem three: Set the parameters in the PreparedStatement, the placeholder settings are hard-coded in Java code, not conducive to system maintenance



Scenario Resolution: Configure SQL statements and placeholders and parameters in an XML file



④, problem four: when traversing the result set from the resultset, there is hard coding for the field of the table, which is not conducive to system maintenance



Imagine resolution: Automatically map the result set of a query to a Java object



⑤, problem Five: Repetitive code is very much, frequent try-catch



Imagine the solution: consolidating it into a try-catch code block



⑥, problem six: cache does very poorly, if there is a large amount of data, this way performance is particularly low



Envision solution: Integrated cache framework to operate database



⑦, question seven: SQL transplant is not good, if you change the database, then the SQL statement may have to rewrite



Scenario: Inserting a third-party framework between JDBC and the database, using a third-party to generate SQL statements, and masking the differences in the database






Since there are so many drawbacks to using JDBC to manipulate databases directly, how do we solve them? Take a look at the introductory example of the MyBatis framework below.



The difference between MyBatis and JDBC


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.