Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
First, Introduction
1. What is MyBatis
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 old Java Objects, ordinary Java objects) to records in a database. (similar to hibernate)
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. It supports an excellent persistence layer framework for plain 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 old Java Objects, ordinary Java objects) to records in a database.
2. MyBatis and Hibernate comparison
1) Hibernate is fully automatic, and MyBatis is semi-automatic. Hibernate can achieve the operation of the database through the object relational model, and has the complete mapping structure of JavaBean object and database to generate SQL automatically. While MyBatis has only basic field mappings, object data and actual object relationships still need to be implemented and managed through handwritten SQL.
2) Hibernate database portability is much larger than MyBatis. Hibernate greatly reduces the coupling between objects and databases (Oracle, MySQL, etc.) through its powerful mapping structure and HQL language, and MyBatis because of the need for handwritten SQL, so coupling to the database directly depends on how the programmer writes the SQL. If SQL is not universal and uses a lot of database features, the portability will be much lower and cost-efficient.
3) Hibernate has a complete log system, and MyBatis lacks some. Hibernate log system is very sound, involving a wide range, including: SQL Records, relationship anomalies, optimization warnings, cache hints, dirty data warning, and MyBatis in addition to the basic record function, the function is much weaker.
4) MyBatis needs to be concerned with many details compared to hibernate. Hibernate configuration is more complicated than mybatis, and the learning cost is higher than mybatis. But it is also because MyBatis is easy to use, which leads to a lot of technical details than hibernate. MyBatis because of the lack of detail, the development model with the traditional JDBC is very small, so it is easy to get started and develop projects, but ignoring the details will lead to more early project bugs, so the development of relatively stable software is very slow, and the development of software is very fast. Hibernate is just the opposite. But if you use hibernate very skillfully, actually the development efficiency tittle even surpasses mybatis.
5) for SQL Direct optimization, MyBatis is much more convenient than hibernate. Because MyBatis SQL is written in XML, optimizing SQL is much easier than hibernate. and hibernate SQL Many are automatically generated, can not directly maintain SQL, although there is hql, but the function is not as strong as SQL, see reports and other abnormal needs, HQL also take a break, that is, HQL is limited; hibernate supports native SQL, though. But the development model is different from ORM, need to change thinking, so it is not very convenient to use. In short, the flexibility of writing SQL on Hibernate is less than MyBatis. 6) Hibernate has a better level two caching mechanism and can use third-party caches. MyBatis's level Two cache mechanism is poor.
Ii. Examples of Use
Project free Download
1. Open MySQL and create a new table.
Use Test;create table t_employeer (employeer_id int NOT null primary key auto_increment, employeer_name varchar () de Fault Null,employeer_age int default null,employeer_department varchar (+) default Null,employeer_worktype varchar ( () default null)
2. Create a new Java project and import the required packages. Mybatis-3.2.8.jar+mysql-connector-java-5.1.22-bin.jar
3. Create a new mybatis configuration file:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <!--This is the root tag--><configuration><!--element allows a file of the properties format to be provided outside the main profile, making the master profile more generic. This is useful for deployment--><!--<properties resource= "mysql.properties"/>--><!--setting aliases, be sure to place them under properties-->& Lt;typealiases><typealias alias= "Employeer" type= "Com.mucfc.model.Employeer"/></typealiases><! --Configure Data source related information--><environments default= "development" ><environment id= "development" >< TransactionManager type= "JDBC"/><datasource type= "pooled" ><property name= "Driver" value= " Com.mysql.jdbc.Driver "/> <property name=" url "value=" jdbc:mysql://localhost:3306/test?characterencoding= UTF-8 "/> <property name=" username "value=" root "/> <property name=" password "value=" [email protected ] "/> <!--<property name=" Driver "value=" ${driver} "/><propertY name= "url" value= "${url}"/><property name= "username" value= "${username}"/><property name= "password" Value= "${password}"/>--></datasource></environment></environments><!--list map Files-- <mappers><mapper resource= "Com/mucfc/model/employeer.xml"/></mappers></configuration>
The configuration method of the data source can also be written as:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <!--This is the root tag--><configuration><!--element allows a file of the properties format to be provided outside the main profile, making the master profile more generic. This is useful for deployments--<properties resource= "mysql.properties"/> <!--setting aliases, be sure to place them under properties-->< Typealiases><typealias alias= "Employeer" type= "Com.mucfc.model.Employeer"/></typealiases><!-- Configure Data source-related information--><environments default= "development" ><environment id= "development" >< TransactionManager type= "JDBC"/><datasource type= "pooled" ><!--<property name= "Driver" value= " Com.mysql.jdbc.Driver "/> <property name=" url "value=" jdbc:mysql://localhost:3306/test?characterencoding= UTF-8 "/> <property name=" username "value=" root "/> <property name=" password "value=" [email protected ] "/>--><property name=" Driver "value=" ${driver} "/><property Name= "url" value= "${url}"/><property name= "username" value= "${username}"/><property name= "password" value= "${password}"/> </dataSource></environment></environments><!--listing mapping files--><mappers ><mapper resource= "Com/mucfc/model/employeer.xml"/></mappers></configuration>
Mysql.properties as follows:
Driver=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/test?charset=utf8username=root[email protected]
Both of the above methods can be used, but only one at a time.
3. The class corresponding to the new table:
Package Com.mucfc.model;import java.io.serializable;/** * Employee Information class * @author Linbingwen * @time 2015.5.11 */public class Emplo Yeer {private Integer employeer_id;private string employeer_name;private integer employeer_age;p rivate string employeer _department;private String employeer_worktype;public Employeer () {super ();} Public Integer getemployeer_id () {return employeer_id;} public void setemployeer_id (Integer employeer_id) {this.employeer_id = employeer_id;} Public String Getemployeer_name () {return employeer_name;} public void Setemployeer_name (String employeer_name) {this.employeer_name = Employeer_name;} Public Integer Getemployeer_age () {return employeer_age;} public void Setemployeer_age (Integer employeer_age) {this.employeer_age = Employeer_age;} Public String getemployeer_department () {return employeer_department;} public void Setemployeer_department (String employeer_department) {this.employeer_department = employeer_department;} Public String Getemployeer_worktype () {return employeer_worktyPE;} public void Setemployeer_worktype (String employeer_worktype) {this.employeer_worktype = Employeer_worktype;} @Overridepublic String toString () {return "Employeer [employeer_id=" + employeer_id + ", employeer_name=" + employeer_name + ", employeer_age=" + employeer_age+ ", employeer_department=" + employeer_department+ ", employeer_worktype=" + Employe Er_worktype + "]";}}
4, configuration data mapping, this is a key content of this article
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < Mapper namespace= "Com.mucfc.model.EmployeerMapper" > <!--Find-<select id= "Findemployeerbyid" Parame tertype= "int" resulttype= "Employeer" > select* from ' t_employeer ' where employeer_id =#{employeer_id} </selec T> <!--plug-in <!--Usegeneratedkeys is set to "true" to indicate that you want to mybatis the primary key generated by the database automatically; keyproperty= "id" specifies the master Key value injected to Employeer ID Property--<insert id= "Addemployeer" parametertype= "Employeer" usegeneratedkeys= "true" Keyproper ty= "employeer_id" > insert INTO ' t_employeer ' (Employeer_name,employeer_age,employeer_department,employeer_workt ype) VALUES (#{employeer_name},#{employeer_age},#{employeer_department},#{employeer_worktype}) </insert> <!--Remove--<delete id= "Deleteemployeer" parametertype= "int" > Delete fRom ' t_employeer ' where employeer_id = #{employeer_id} </delete> <!--Modified--<update id= "Updateemployeer" parametertype= "Employeer" > Update t_employeer Set employeer_name = #{employeer_name},employe er_age= #{employeer_age},employeer_department = #{employeer_department}, Employeer_worktype=#{employeer_worktype} where employeer_id = #{employeer_id} </update> </mapper>
5. Test class:
Package Com.mucfc.test;import Java.io.ioexception;import Java.io.reader;import org.apache.ibatis.io.Resources; Import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;import Com.mucfc.model.employeer;public class MybatisTest { private static sqlsessionfactory sqlsessionfactory;private static reader reader;static {try {reader = Resources.getresourceasreader ("Mybatis-config.xml"); sqlsessionfactory = new Sqlsessionfactorybuilder (). Build ( Reader);} catch (Exception e) {e.printstacktrace ();}} /** * Find */public static void Findemployeerbyid (int id) {sqlsession session = Null;try {session = Sqlsessionfactory.opense Ssion (); Employeer employeer = (employeer) session.selectone ("Com.mucfc.model.EmployeerMapper.findEmployeerByID", 1); if ( Employeer = = null) SYSTEM.OUT.PRINTLN ("null"); ElseSystem.out.println (employeer);} finally {session.close ();}} /** * Add */public static void Addemployeer (Employeer employeer) {sqlsession Session = Null;try {session = Sqlsessionfactory.opensession ();//return value is the number of record bars int resultcount = Sessio N.insert ("Com.mucfc.model.EmployeerMapper.addEmployeer", employeer); System.out.printf ("Currently inserted employeer_id:%d currently inserted in database:%d", employeer.getemployeer_id (), resultcount); Gets the ID of the inserted object System.out.println (""); Session.commit (); } finally {session.close ();}} /** * Delete * */public static void deleteemployeer (int id) {sqlsession session = Null;try {session = Sqlsessionfactory.opense Ssion (); The return value is the number of record bars int resultcount=session.delete ("Com.mucfc.model.EmployeerMapper.deleteEmployeer", id); System.out.println ("The number of bars currently in the database deleted:" +resultcount); Gets the ID of the inserted object Session.commit (); } finally {session.close ();}} /** * Change */public static void Updateemployeer (Employeer employeer) {sqlsession session = Null;try {session = Sqlsessionfact Ory.opensession (); Session.update ("Com.mucfc.model.EmployeerMapper.updateEmployeer", EmployeER); Session.commit (); } finally {session.close ();}} public static void Main (string[] args) {employeer employeer1=new employeer (); Employeer1.setemployeer_name ("John Doe"); Employeer1.setemployeer_age, Employeer1.setemployeer_department ("Product part"); Employeer1.setemployeer_worktype (" Development engineer "); Employeer employeer2=new Employeer () employeer2.setemployeer_name ("Zhang San"); Employeer2.setemployeer_age (30); Employeer2.setemployeer_department ("Product Two"); Employeer2.setemployeer_worktype ("Test Engineer"); Employeer employeer3=new Employeer () employeer3.setemployeer_name ("Xiao Wang"); Employeer3.setemployeer_age (22); Employeer3.setemployeer_department ("Part Three"); Employeer3.setemployeer_worktype ("Data Analyst"); Employeer employeer4=new Employeer () employeer4.setemployeer_name ("Ming"); Employeer4.setemployeer_age (22); Employeer4.setemployeer_department ("accounting department"); Employeer4.setemployeer_worktype ("Financial officer");//Insert Addemployeer (employeer1 ); Addemployeer (Employeer2); Addemployeer (Employeer3); Addemployeer (employeer4);//Find Findemployeerbyid (1);//deleteExcept Deleteemployeer (1);//Change employeer2.setemployeer_id (2); Employeer2.setemployeer_age (+); employeer2.setemployeer_ Department ("Part Three"); Updateemployeer (Employeer2);}}
One of the following to analyze
(1) Insert Test
Function:
/** * Add */public static void Addemployeer (Employeer employeer) {sqlsession session = Null;try {session = Sqlsessionfactory . Opensession (); The return value is the number of record bars int resultcount = Session.insert ("Com.mucfc.model.EmployeerMapper.addEmployeer", employeer); System.out.printf ("Currently inserted employeer_id:%d currently inserted in database:%d", employeer.getemployeer_id (), resultcount); Gets the ID of the inserted object System.out.println (""); Session.commit (); } finally {session.close ();}}
Call
Insert Addemployeer (employeer1); Addemployeer (Employeer2); Addemployeer (Employeer3); Addemployeer (EMPLOYEER4);
Results in database:
(2) Find the test, then insert the test above:
Function:
/** * Find */public static void Findemployeerbyid (int id) {sqlsession session = Null;try {session = Sqlsessionfactory.opense Ssion (); Employeer employeer = (employeer) session.selectone ("Com.mucfc.model.EmployeerMapper.findEmployeerByID", 1); if ( Employeer = = null) SYSTEM.OUT.PRINTLN ("null"); ElseSystem.out.println (employeer);} finally {session.close ();}}
Call:
Find Findemployeerbyid (1);
Results
(3) Delete the test, connect the above
where functions:
/** * Delete * */public static void deleteemployeer (int id) {sqlsession session = Null;try {session = Sqlsessionfactory.ope Nsession (); The return value is the number of record bars int resultcount=session.delete ("Com.mucfc.model.EmployeerMapper.deleteEmployeer", id); System.out.println ("The number of bars currently in the database deleted:" +resultcount); Gets the ID of the inserted object session.commit (); } finally {session.close ();}}
Call
Deleteemployeer (1);
Results
The 1th record was deleted.
(4) Modify the data
This is before
Function:
/** * Change */public static void Updateemployeer (Employeer employeer) {sqlsession session = Null;try {session = Sqlsessionfact Ory.opensession (); Session.update ("Com.mucfc.model.EmployeerMapper.updateEmployeer", employeer); Session.commit (); } finally {session.close ();}}
Call:
Change of employeer2.setemployeer_id (2); Employeer2.setemployeer_age (+) employeer2.setemployeer_department ("Product three"); Updateemployeer (EMPLOYEER2);
This is after
Zhang San's information was successfully changed
Project free Download
Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
"Mybatis" Mybatis Introductory Overview and the first Mybatis instance implementation additions and deletions