MyBatis detailed (i)------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.

2. Why do you have 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 drive public static string driverclass = "Com.mysql.jdbc.Driver";//mysql User name public static string userName = "root";//mysql password public static string PassWord = "root";//mysql urlpublic static string url = "Jdbc:mysql://localhost:3306/test";//define Database connection public static Connection conn = null;//Define Declaration database statement, use precompiled declaration PreparedStatement improve database performance public static PreparedStatement PS = null;// Define return result set public static ResultSet rs = null;/** * Query Person Table information * @return: Returns the list collection of person */public static list<person& Gt Readperson () {list<person> List = new arraylist<> (); try {//Load Database driver Class.forName (driverclass);// Get database Connection conn = drivermanager.getconnection (URL, userName, passWord);//Define the SQL statement,? represents a placeholder String sql = "SELECT * from the person where pname=?"; /Get precompiled processing of STATEMENTPS = conn.preparestatement (sql);//Set the parameters in the SQL statement, the first one for the parameters in the SQL statement? (starting from 1), the second set parameter value ps.setstring (1, "Qzy");//Issue SQL statement query to database and return 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 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 ());}}

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.

MyBatis detailed (i)------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.