MyBatis的学习与理解

来源:互联网 发布:撤销网络问政的投诉 编辑:程序博客网 时间:2024/05/20 22:01

一:

进入到公司发现公司用的框架式SSi,Spring和Struts都学过,可是MyBatis还真不知道,可是马上就要做项目了,不得不学啊,下面是我对MyBatis的简单理解。

1>:为什吗要用Mybatis而不用hibernate做持久层框架?

    首先我们来区分一下hibernate与mybatis的区别:

   hibernate:优化难度比较大,配置比较困难,但搭好框架后开发效率比mybatis高很多

   mybatis:对sql细节更容易控制,但是写sql比较耗时,要控制好查询sql的重用比较难,造成开发效率较低。

   如果大家想要详细的了解一下他们的区别:请看http://hi.baidu.com/mlt_zlf/item/08cbe312662eb98688a956e8。

2>:MyBatis的定义:

    MyBatis is a first class persistence framework with support for custom SQL, stored procedures

  and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of

  parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration

  and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.如果看不懂建百 度。

3>:MyBatis框架的搭建:

   首先我们去MyBatis的官网上下载所需要的Jar:http://www.mybatis.org/本次DEMO用到的环境是:Myeclipse8.5,Oracle所以我们还需要用到OJDBC.jar

我们首先在数据库中间张person的表:

create table person(id number primary key not null,name varchar2(20),sex varchar2(10),age number)

然后随便插入一些数据,这里省略。

然后再我们的src下建对应的POJO类,这里我就不再浪费笔墨了。

下面主要来认识一下Configuration.xml和sql.xml

Configuration.xml
我们一看到下面的内容可能会有莫名的亲切感,那是肯定的了,从JDBC类,到hibernate.cfg.xml到Spring中ApplicationContext.xml到JDBC.properties我们配置了无数遍,只不过是标签改变了一下,环境变了。相信不用多解释,大家也理解了。

<configuration>     <environments default="myexample">        <environment id="myexample">              <transactionManager type="JDBC" />              <dataSource type="POOLED">                  <property name="driver" value="oracle.jdbc.driver.OracleDriver" />                 <property name="url" value="jdbc:oracle:thin:@192.168.0.205:1521:orcl" />                  <property name="username" value="sjgl" />                <property name="password" value="hncx" />             </dataSource>         </environment>      </environments>     <mappers>          <mapper resource="com/jzh/model/sql.xml"/>      </mappers>  </configuration> 

下面我们来看一下SQl.xml

我们需要了解几个定义:

id:A unique identifier in this namespace that can be used to reference this statement

parameterType:The fully qualified class name or alias for the parameter that will be passed into this statement

resultType:The fully qualified class name or alias for the expected type that will be returned from this statement. Note
                        that in the case of collections, this should be the
                       type that the collection contains, not the type of the
                        collection itself. Use resultType OR resultMap,not both.

其实常用的就这几个,如果大家感兴趣的话可以再继续了解:

<?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.jzh.model.Person">       <select id="selectPersonName" parameterType="String" resultType="com.jzh.model.Person">         select * from person where name=#{name}   </select>    <select id="selectPersonName2" parameterType="object" resultType="com.jzh.model.Person">         select * from person        <where>       <if test="name !=null and name!=''">          name=#{name}       </if>       </where>   </select>     <select id="selectPersonName3" parameterType="hashmap" resultType="com.jzh.model.Person">         select * from person        <where>       <if test="name !=null and name!=''">          name=#{name}       </if>       </where>   </select>     <insert id="insertPerson" parameterType="com.jzh.model.Person">    insert into person(id,name,sex,age) values(#{id},#{name},#{sex},#{age})   </insert>  <update id="updatePerson" parameterType="com.jzh.model.Person">   update person set name=#{name} , sex=#{sex}   <where>      <if test="id!=null and id!=''">  id=#{id}  </if>  </where>   </update>   <delete id="deletePerson" parameterType="String">         delete from person where name=#{name}          </delete>  </mapper>

我们来看看这个Test类

public class Test {/** * @param args */public static void main(String[] args) {SqlSessionFactory factory = null;           try {              factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("Configuration.xml"));          } catch (IOException e) {         e.printStackTrace();        }         SqlSession sqlSession = factory.openSession();      /*       * select  :String       */      String name="haha";      Person p = (Person) sqlSession.selectOne("com.jzh.model.PersonInfo.selectPersonName", name);       /*       * select  :map           */      Map map=new HashMap();      map.put("name", name);      Person pmap = (Person) sqlSession.selectOne("com.jzh.model.Person.selectPersonName3", map);      /*       * select  :Object       */      Person person=new Person();      person.setName(name);      //如果我们在sql中用到了test,那马我们必须传对象过去,ParameterType="Object"      Person pObject = (Person) sqlSession.selectOne("com.jzh.model.Person.selectPersonName2", person);          /*      * insert      */     Person p1=new Person();     p1.setAge(22);     p1.setId(2);     p1.setName("haha");     p1.setSex("男");     sqlSession.insert("com.jzh.model.PersonInfo.insertPerson",p1);     /*      * update      */         p.setName("xie");     p.setSex("女");     sqlSession.update("com.jzh.model.PersonInfo.updatePerson", p);     /*      * delete      */     sqlSession.delete("com.jzh.model.PersonInfo.deletePerson", "xie");     sqlSession.commit();     System.out.println("hahahah");     sqlSession.commit();     System.out.println(p.getName());      }}