The first HelloWorld of MyBatis

Source: Internet
Author: User
Tags cdata

Hibernate and MyBatis are both ORM's framework, first to post a wave of their own understanding of the two frameworks, if there is a mistake to welcome correct:

Hibernate makes it easy to map the PO class to the database table, and hibernate encapsulates SQL, preferring traditional database operations to object-oriented thinking, and developers do not need to know a lot about database knowledge when manipulating databases. Because hibernate will automatically generate SQL statements, this is the advantage of hibernate is also his shortcomings, after all, the framework is for program development, considering that most of the usage scenarios, it is impossible to do a lot of SQL statement optimization, But if developers use hibernate to execute their own SQL statements, this is not an option, but it will also conflict with the architecture of the project as a whole, which is why hibernate loses the use of his meaning, and mybatis allows developers to use their own SQL statements. and users can tune their own. and hibernate's support for caching is richer than MyBatis, Hibernate has its own logging, and mybatis needs to use a third-party log jar file, often log4j, and personally think that Hibernate and MyBatis the use of the scene is very different, as to use which is entirely in the developer to choose, as for the current software development area extremely despise SSH sought after springmvc+spring+mybatis, I think both is a good framework, The key is to use the scene, to complete the required functions, in fact, the use of which development process is the same.

Here's a wave of other people's descriptions of the pros and cons of Hibernate and MyBatis:


Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Source: Know
1, development and comparison of development speed

Hibernate's real mastery is more difficult than mybatis. The MyBatis framework is relatively simple and easy to get started with, but also relatively rudimentary. Personally think to use good mybatis or first to understand good hibernate first.

Development Community

Hibernate and MyBatis are popular persistent layer development frameworks, but the hibernate development community is relatively lively, supported by a number of tools, updated quickly, the current highest version of 4.1.8. The mybatis is relatively calm, with fewer tools and currently the highest version of 3.2.

Development effort

Both hibernate and MyBatis have corresponding code generation tools. A simple basic DAO layer method can be generated.

For advanced queries, MyBatis needs to write SQL statements manually, as well as Resultmap. Hibernate has a good mapping mechanism, and developers don't have to worry about SQL generation and result mapping, and can focus more on business processes.

2, System tuning contrast Hibernate's tuning scheme
    1. Develop a reasonable caching strategy;
    2. Use lazy loading features as much as possible;
    3. The use of reasonable session management mechanism;
    4. Use batch fetch, set reasonable batch processing parameters (Batch_size);
    5. Make a reasonable design of O/R mapping
MyBatis Tuning Solution

MyBatis in session and Hibernate session life cycle is consistent, also need a reasonable session management mechanism. The MyBatis also has a two-level caching mechanism. MyBatis can perform detailed SQL optimization design.

SQL optimization aspects

Hibernate queries query all the fields in the table, which can be a performance drain. Hibernate can also write its own SQL to specify the fields that need to be queried, but this undermines the simplicity of hibernate development. The MyBatis SQL is written manually, so you can specify the fields of the query on demand.

The tuning of Hibernate HQL statements requires that SQL be printed out, and Hibernate's SQL is too ugly for many people to dislike. MyBatis's SQL is written manually, so it's easy to adjust. However, hibernate has its own log statistics. The mybatis itself does not have log statistics and uses log4j to log records.

Extensibility aspects

Hibernate's association with a specific database can only be configured in an XML file, and all HQL statements are not relevant to the database in use and are well-ported. All SQL statements in the MyBatis project are dependent on the database used, so support for different database types is not good.

3. Object management and crawl policy object management

Hibernate is a complete object/relational mapping solution that provides the functionality of object state Management (management), which eliminates the need for developers to heed the details of the underlying database system. That is, hibernate uses a more natural object-oriented perspective to persist data in Java applications relative to the common Jdbc/sql persistence layer scenarios in which SQL statements need to be managed.

In other words, developers using Hibernate should always focus on the state of the object, regardless of the execution of the SQL statement. This part of the details has been managed by Hibernate and only needs to be understood by the developer when it comes to tuning the system performance.

And MyBatis in this one. There is no document stating that the user needs to manage the object in detail.

Crawl strategy

Hibernate has a good mechanism for capturing entity-related objects. For each correlation relationship can be set in detail whether delay loading, and provide related crawl, query fetch, subquery fetch, batch crawl four modes. It is configured and processed in detail.

The deferred load for MyBatis is globally configured.

4. Cache mechanism vs. hibernate cache

Hibernate buffer is the session cache, the use of a good first-level cache will need to manage the session life cycle. We recommend that you use a session in an action action. First-level caching requires strict management of the session.

Hibernate level Two caches are sessionfactory-level caches. The sessionfactory cache is divided into built-in caches and external caches. The built-in cache holds the data contained in some of the collection properties of the Sessionfactory object (mapping elements and predetermined SQL statements, etc.), which is read-only for the application. The external cache holds a copy of the database data, which acts like a first-level cache. Level two cache in addition to memory as a storage medium, you can also choose the hard disk and other external storage devices. A secondary cache, called a process-level cache or a sessionfactory-level cache, can be shared by all sessions, and its life cycle is accompanied by the existence and extinction of the sessionfactory life cycle.

5. Comparative advantage

MyBatis Advantages
    • MyBatis can perform more granular SQL optimizations and can reduce query fields.
    • The MyBatis is easy to master, while the hibernate threshold is higher.
Hibernate Advantage
    • Hibernate's DAO layer development is simpler than mybatis, and mybatis needs to maintain SQL and result mappings.
    • Hibernate to the object maintenance and caching is better than MyBatis, to delete and change the object of the maintenance to be convenient.
    • Hibernate database portability is very good, MyBatis database portability is bad, different databases need to write different SQL.
    • Hibernate has a better level two caching mechanism and can use third-party caches. The caching mechanism provided by the MyBatis itself is poor.
individuals feel that learning must be a gradual stage, it is recommended to learn mybatis, after all, the study cost is lower, and the official Chinese official Description: Description Address: http://www.mybatis.org/mybatis-3/zh/getting-started.html

Hibernate description Document: It is not affixed, very easy to find, direct Baidu can

Anyway, the first hibernate program, because I have just learned, and rarely found on the internet, mybatis about the database connection pool code configuration, here does not paste, do not use database connection pool:
First step: Import jar Package: Mybatis-3.2.3.jar, database-driven, MySQL database is used here

In the second step, you write the PO class and the mapping file, you can manipulate the database using the map file, or you can use an interface instance to do this:

Po class:

Package com.leige.domain;    public class  Student {      private Integer sid;      private String name;      Private Integer age;                Setter:                 Getter ...  }  

SQL mapping File:
<?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" > <!- -namespace is the implementation of SQL isolation, the operation of an object SQL statement in a namespace here the call query is Student.selectstudentbyid---<mapper namespace= "Student" &  Gt <!--follow the SID query database with the simple name of the simple PO class, provided that the alias <typeAliases> <typealias alias= "is configured in the configuration Stu Dent "type=" Com.leige.domain.Student "/> </typeAliases> <select id=" Selectstudentbyid "Paramete rtype= "int" resulttype= "Student" > <! [cdata[SELECT * FROM student where sid = #{sid}]]> </select> <select id= "selectstudent ByName "parametertype=" java.lang.String "resulttype=" Student "> <!--'%${value}% ' means string concatenation, note that the name of the placeholder is not called the property name of the Po class,         Out of the ID, otherwise it will error there is no getters for the property named ' xxx ' in ' class java.lang.String ' but not recommended, will produce SQL injection <! [cdata[SELECT * from STudent where name like '%${value}% ']]> </select> <!--Increase--<insert id= "in Sertstudent "parametertype=" Student "> <!--Configure primary key auto-increment return, must be executed with INSERT statement to use Order: represents the order of execution of the statement relative to insert Resulttype : Return result type, must configure MySQL function select last_insert_id () can query-<selectkey keyproperty= "Sid" Order= "after" result type= "int" > <! [cdata[SELECT last_insert_id ()]]> </selectKey> <!--non-self-increment primary key return Back to <selectkey keyproperty= "Sid" Order= "after" resulttype= "java.lang.String" > <! [cdata[SELECT UUID ()]]> </selectKey>-<!   [cdata[INSERT into student (Sid,name,age) VALUES (#{sid},#{name},#{age})]]> </insert> <!-- Delete--<delete id= "Deletestudentbyid" parametertype= "int" > <! [cdata[Delete from student where Sid=#{sid}       ]]> </delete> <!--update-<delete id= "updatestudent" parametertype= "Student" > <!    [cdata[update student set Name=#{name},age=#{age} where Sid=#{sid}]]> </delete> </mapper>

Interface Operation Example:
Package com.leige.domain;    Import java.util.List;  Import Org.apache.ibatis.annotations.Delete;  Import Org.apache.ibatis.annotations.Select;  Import Org.apache.ibatis.annotations.SelectKey;        Import Org.apache.ibatis.annotations.Update; Public interface Studentmapper {//id lookup @Select ("SELECT * from student where Sid=#{sid}") Public student SE      Lectstudent (Integer ID); Add @SelectKey (before=false,keyproperty= "Sid", statement= "select last_insert_id ()", Resulttype =int.class) @Sele      CT ("INSERT into student (Sid,name,age) VALUES (#{sid},#{name},#{age})") public void Addstudent (student student); Find multiple @Select ("SELECT * from student where name is like '%${value}% '") Public list<student> Selectstudentbyna      Me (String name);      Delete @Delete ("Delete from student where Sid=#{value}") public void Deletestudentbyid (Integer sid); Update @Update ("Update student set Name=#{name},age=#{age} where Sid=#{sid}") public void UPdate (Student Student);   }


<?xml version= "1.0" encoding= "UTF-8"?> <!  DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <!--loading jdbcproperties to be written between the configuration and environment--<properties Resou Rce= "Com/leige/config/jdbcinfo.properties" ></properties> <!--alias declarations, telling mybatis,student the corresponding class type so that it can Studen T this character and the student class correspond to type aliases that set a short name for the Java type.          It is only relevant to the XML configuration, and the only thing that exists is to reduce the redundancy of the class fully qualified name, which can be used anywhere you need to use com.leige.domain.Student student-<typeAliases> <typealias alias= "Student" type= "com.leige.domain.Student"/> </typeAliases> <!--environment configuration, database connection Parameters--<environments default= "Development" > <environment id= "Development" > <trans ActionManager type= "JDBC"/> <datasource type= "Pooled" > <property name= "Driver" value= "${driver } "/> <property name=" url "value=" ${uRL} "/> <property name=" username "value=" ${username} "/> <property name=" password "value=" ${pa ssWOrd} "/> </dataSource> </environment> </environments> <!--Add the operation SQL collection to the configuration file-- > <mappers> <mapper resource= "Com/leige/domain/studentmapper.xml"/> </mappers> </confi   Guration>
JDBC Configuration parameters:

Driver=com.mysql.jdbc.driver  url=jdbc\:mysql\:///test  username=root  password=  

The third step is to write the tool class, reduce the code, and achieve the function of getting session sessions and getting the operation instance:

Package com.leige.test;  Import java.io.IOException;    Import Java.io.InputStream;  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 Org.junit.Test;      /** * @author sqlsession Tool Class * */public class Sqlutils {static Sqlsessionfactory factory;          Static loading session factory static{InputStream InputStream;              try {InputStream = Resources.getresourceasstream ("Com/leige/config/configuration.xml");          1: Instantiate Sqlsessionfactory factory factory= New Sqlsessionfactorybuilder (). Build (InputStream);                } catch (IOException e) {}} public static sqlsession getsession () {try{          Open session return Factory.opensession ();          }catch (Exception e) {throw new RuntimeException (e);    }      }  /** * @param session * @param mapper * @return * Ensure the session is consistent, so as a parameter pass * * Public St atic Object getmamapper (sqlsession session,class Mapper) {//Register Map Interface Factory.getconfiguration (). AddM          Apper (mapper);      Returns the operation instance return Session.getmapper (mapper);   }    }

Test class:

Package com.leige.test;  Import Java.io.InputStream;    Import java.util.List;  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 Org.junit.Test;  Import com.leige.domain.Student;    Import Com.leige.domain.StudentMapper;                public class App {/** * @throws query a single object based on ID */@Test public void Fun () throws exception{              InputStream Inputstream=resources.getresourceasstream ("Configuration.xml");              1: Instantiate Sqlsessionfactory factory sqlsessionfactory factory= new Sqlsessionfactorybuilder (). Build (InputStream);              2: Register Interface//factory.getconfiguration (). Addmapper (Studentmapper.class);              3: Open session sqlsession session=factory.opensession (); 4:1 There are two ways to manipulate a database: A namespace plus a named statement execution//system.out.println (Session.selectone ("StUdent.selectstudent ", 1)); /* The second is to operate the database using the Operation interface * but you need to register the interface, and the interface needs to declare the action statement with annotations * that is, the statement required to register execution on the interface @select ("SELECT * FROM Student wher                E sid=#{id} ") * *///Register Interface Factory.getconfiguration (). Addmapper (Studentmapper.class); Get Mapper Instance Studentmapper studentmapper= (studentmapper) session.getmapper (Studentmapper.class)                ;              Query Database System.out.println (studentmapper.selectstudent (1));            Session.close (); /** * Test finds multiple */@Test public void Testfindbyname () {try {//Through tool class               Get session sqlsession Session=sqlutils.getsession ();                      List<student> Students=null; The first way: a namespace lookup, or you can use a map instance lookup, SelectList find multiple//students=session.selectlist ("Student.selectstudentbyname                  "," Leige "); The second way Studentmapper mapper=(Studentmapper)                 Sqlutils.getmamapper (Session,studentmapper.class);         Students=mapper.selectstudentbyname ("Leige");          Print information for (Student stu:students) System.out.println (Stu);          } catch (Exception e) {//TODO auto-generated catch block System.out.println (e); }}/** * Test increase */@Test public void Testinsert () {//Get session through tool class Sqlsess      Ion Session=sqlutils.getsession ();      Student student=new Student ();      Student.setage (22);        Student.setname ("Leige3");      The first way: Perform the INSERT, using the XML configuration in SQL parameter//session.insert ("Student.insertstudent", Student);      The second insert, using the SQL parameters in the interface file Studentmapper mapper= (studentmapper) Sqlutils.getmamapper (session, Studentmapper.class);      Mapper.addstudent (student);      The output returns the primary key System.out.println (Student.getsid ());      Notice when the query does not need to submit, do delete and change the need to submit in order to be effective session.commit ();    Close session session.close ();  }/** * Test Delete */@Test public void Testdelete () {//Get session SQL          Session session=sqlutils.getsession ();          The first way: Perform the delete, using the XML configuration in SQL parameter Session.delete ("Student.deletestudentbyid", 12);          The second deletion, using the SQL parameters in the interface file Studentmapper mapper= (studentmapper) Sqlutils.getmamapper (session, Studentmapper.class);          Mapper.deletestudentbyid (13);          Submit Session.commit ();      Close Session.close (); }/** * Test update */@Test public void Testupdate () {//Get session Sqlsession          Session=sqlutils.getsession ();          Here do not query database, directly modified Student student=new Student ();          Student.setsid (1);          Student.setage (21);            Student.setname ("Leige23");          The first way: Perform the update, using the XML configuration in SQL parameter//session.update ("Student.updatestudent", Student); Second update, using the SQL parameter in the interface file Studentmapper mapper= (studentmapper) SQlutils.getmamapper (session, Studentmapper.class);          Mapper.update (student);          Submit Session.commit ();      Close Session.close ();   }  }

Create a database table, needless to say


The first HelloWorld of MyBatis

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.