Preface
The persistence layer of the new company's new project was used by MyBatis, and I've been using hibernate for the past year or two, and there's been a controversy about the two frameworks, some say that hibernate is too bloated and inefficient than mybatis, It is also said that hibernate optimization is as good as the efficiency, but I still think that each has the advantage, such as Hibernate API can let us ignore the database porting, HQL also simplifies the SQL, but MyBatis is really slightly more flexible than hibernate, As long as it is not using JDBC, these frameworks should all be about the same, and nothing more than a good and bad problem. Just into the company that array Yang once told me, will hibernate words to learn mybatis is a few hours of things, it seems to be so, whether the whole structure or use of methods are expatiating, this blog is my first study mybatis, so write a simple crud , of course, my this series of blog also has a feature is to continue and hibernate to do a comparison, while summarizing the review hibernate, while learning to record MyBatis.
first knowledge of MyBatis
First look at the engineering structure of MyBatis,
Give me the first feeling is lightweight, jar package only need 2, and no dependence, then look at Hibernate engineering structure,
In contrast, the "light" is the "weight" at a glance. Again specific look at the structure of the package, it is not difficult to find mybatis under a mappers package, which is put in an XML file, not learned should also have heard that the MyBatis SQL statement is written in the configuration file independently, And it is written in these mapper.xml files, and this later in detail. No matter which frame naturally should have a whole configuration file, just like hibernate in Hibernate.cfg.xml, let's look at the mybatis-config.xml of MyBatis:
<?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><typealiases><typealias alias= "User" type= "Com.wl.entity.User"/></ Typealiases><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://127.0.0.1:3306/TESTDB2 "/><property Name= "username" value= "root"/><property name= "password" value= "11fit"/></datasource></ Environment></environments><mappers><mapper resource= "Com/wl/mappers/user_mapper.xml"/> </mappers></configuration>
Basically and Hibernate configuration method exactly the same, data source, mapper file (hbm file), the only thing to note is that there is a <typealiases> configured here, this configuration is also very well understood, is We have configured an alias for our entity Bean , and in the later Mapper.xml we don't have to bring the package name if we need to introduce the user, otherwise we must write the full package name + class name.
The following focus is on the entity class and the Mapper file, in Hibernate, our entity class will inevitably have a mapping file (hbm.xml) or map annotations (@Entity @Table) corresponding, they declare the properties of our entity bean and database field corresponding way, Data types and so on, and in MyBatis, this is still true, and in addition to these, MyBatis also puts SQL statements into this configuration file. Let's take a look at User_mapper.xml this configuration 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" >< Mapper namespace= "Com.wl.entity.UserMapper" ><!--by <resultMap> mapping entity class Property names and table field names--><resultmap Type= "User" id= "Userresultmap" ><!--using the id attribute to map the primary key field--><id property= "id" column= "userId"/><result property= "name" column= "UserName"/><result property= "pwd" column= "userpwd"/><result property= "birthday "Column=" Userborn "/></resultmap><select id=" Selectuserbyid "parametertype=" int "resultMap=" Userresultmap ">select * from t_user where userId = #{id}</select><insert id=" Insertuser "parametertype=" User "usegeneratedkeys=" true "keyproperty=" UserId ">insert into T_user (Username,userpwd,userborn) VALUES (#{name}, #{pwd},#{birthday}) </insert><delete id= "DeleteUser" parametertype= "int" >delete from t_user whereuserId = #{id}</delete><update id= "UpdateUser"Parametertype= "User" >update t_user set Username= #{name} where userId = #{id}</update></mapper>
First of all, take a look at the top of the <resultMap> configuration is very similar to hibernate in the configuration of hibernate-mapping, casually find a hibernate hbm files to see:
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd ">
that is, the corresponding relationship between the entity attribute and the database field is declared. Back to continue to see MyBatis Mapper file, below can see <select>, <insert>, <delete>, <update> these configurations, not difficult to understand, Each database statement is placed into the corresponding configuration tag. Then look at the configuration of the parameters in these configurations, such as:<select id= "Selectuserbyid" parametertype= "int" resultmap= "Userresultmap" >
It is not difficult to find that every SQL statement has an ID, it is the only one we call this SQL credentials, and then look at the outermost <mapper> there is a namespaces configuration, if we configure the namespace, then we need to call SQL through the namespace . sql_id 's combined string is called as a key.
The second configuration parameter is ParameterType, as the name implies nature is the parameter type, this is nothing to say.
The third configuration parameter is Resultmap, this is the focus of configuration, looking back to see where the reference "Userreultmap" is defined? Yes, it is the resultmap defined at the very top of the configuration file that is similar to the Hibernate mapping configuration, and the purpose of configuration is to ensure that the query fields and entity properties correspond . In hibernate we ensure that the ORM map is consistent by configuring <property name= "XXX"/cloumn= "t_xxx" >, which is still true in MyBatis. Of course we can also not configure this resultmap, then we must specify the alias of the query field in SQL to guarantee the same name as the attribute in the entity Bean . In the Resultmap type and SQL configuration in the ParameterType, we are directly using the "User", where no package name is naturally attributed to the one we configured earlier <typealiases>.
And I don't think it's a bit of a placeholder in an SQL statement,hibernate is a placeholder through or:p Aram , and MyBatis is occupied by #{xxx} in an SQL statement . This explains only the configuration and meaning of the standard parameters of <select>, and if any other relevant configuration is used, the official documents must be documented in detail. Well, finally it's time to write our test class and see how we started mybatis and how to invoke the SQL statement:
Package Com.wl.test;import static Org.junit.assert.fail;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.wl.entity.user;public class Test {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 ();}} public static Sqlsessionfactory GetSession () {return sqlsessionfactory;} @org. junit.testpublic void Testquery () {sqlsession session = Sqlsessionfactory.opensession (); try {//query user user = (user) Session.selectone ("Com.wl.entity.UserMapper.selectUserByID", 3); System.out.println ("id-->" + User.getid ()); System.out.println ("name-->" + user.getname ()); System.out.println ("pwd-->" + user.getpwd ()); System.out.println ("Birthday--> "+ user.getbirthday ()); Session.commit ();} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();} finally {session.close ();}}}
is it similar to hibernate, and sessionfactory in hibernate corresponds to the sqlsession in this sqlsessionfactory,hibernate? Including the opening and closing of the session, transaction processing is the same, except that in hibernate we will write HQL or SQL statements in the test, and in MyBatis we directly through the configured SQL ID to invoke the specified SQL can be, You can see that the namespace is indeed passed . sql_id"Way to call, and finally look at the results of the operation:
Can see the successful run, no problems, and additions and deletions are similar, only the core code is posted below:
Add//user user = new User ();//User.setname ("Jack");//USER.SETPWD (111);//SimpleDateFormat SDF = new SimpleDateFormat ( "Yyyy-mm-dd");//User.setbirthday (Sdf.parse ("1992-08-29"));//Session.insert (" Com.wl.entity.UserMapper.insertUser ", user);//delete//Session.delete (" Com.wl.entity.UserMapper.deleteUser ", 1);//Update/ /USER user = (user) Session.selectone (//"Com.wl.entity.UserMapper.selectUserByID", +//User.setname ("Harry");// Session.update ("Com.wl.entity.UserMapper.updateUser", user);
Summary
This is the first lesson in learning MyBatis, only some of the most basic operations, the development of technology are similar to the same, but also for our products or projects to serve a tool, so whether Hibernate or MyBatis, as long as efficiency OK, are desirable, Each frame has the art and beauty of its design, I think. Follow up according to study progress and project progress situation will continue to write MyBatis series blog, also welcome you criticize correct, common exchange! At the same time I will not ignore the pursuit of technology, continuous learning, never stop!
From Hibernate to Mybatis (i)