MyBatis使用

原文鏈接:http://blog.csdn.net/qq_22329521/article/details/75051031

導包

配置sqlMapconfig.xml文件

<?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>
    <!-- 和spring整合后 environments配置將廢除    -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事務管理 -->
            <transactionManager type="JDBC" />
            <!-- 數(shù)據(jù)庫連接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                          value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="" />
            </dataSource>
        </environment>
    </environments>
    <!--Mapper的位置,相當于每個對象的sql的映射文件-->
    <mappers>
        <mapper resource="sqlmap/User.xml"></mapper>
    </mappers>
</configuration>

User.xml

<?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">
<!--寫sql語句-->
<!--namespace命名空間姐浮,避免不同的mapper文件底下有同樣的id的sql方法-->
<mapper namespace="test">
    <!--通過id查詢一個用戶-->
    <select id="findUserById" parameterType="Integer" resultType="com.fmt.mybatis.pojo.User">
       select * from user where id=#{v};
    </select>

    <!--
    #{} 表示占位符()
    ${value} 表示字符串拼接
    -->
    <!--<select id="findUserByName" parameterType="String" resultType="com.fmt.mybatis.pojo.User">-->
       <!--select * from user where username like '%${value}%';-->
    <!--</select>-->
    <!--防止sql注入-->
    <select id="findUserByName" parameterType="String" resultType="com.fmt.mybatis.pojo.User">
        select * from user where username like "%"#{v}"%";
    </select>

    <insert id="addUser" parameterType="com.fmt.mybatis.pojo.User">
         <!-- 添加用戶返回調(diào)用獲取最后插入的id返回給用戶id-->

     <selectKey keyProperty="id" resultType="Integer" order="AFTER">
         select LAST_INSERT_ID()
     </selectKey>
      insert into user (username,birthday,address,sex) VALUE (#{username},#{birthday},#{address},#{sex})
    </insert>

    <update id="updateUserById" parameterType="com.fmt.mybatis.pojo.User">
        update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address}
        where id=#{id}
    </update>
    
    <delete id="deleteUserById" parameterType="Integer">
        DELETE from user where id=#{id}
    </delete>
</mapper>

增刪改查


   @Test
    public void fun1() throws IOException {
//        加載核心配置文件
        String resource="sqlMapConfig.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //創(chuàng)建sqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //創(chuàng)建sqlsession
        SqlSession sqlSession = factory.openSession();
        /**
                User o = sqlSession.selectOne("test.findUserById", 10);
        System.out.println(o);

        List<User> users=sqlSession.selectList("test.findUserByName","五");
        for (User u:users){
            System.out.println(u);
        }
        */
        /**
              User user = new User();
        user.setAddress("北京");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setUsername("富媒體");
        int i= sqlSession.insert("test.addUser",user);
        sqlSession.commit();

        Integer id = user.getId();
        System.out.println(id);
        */
        /**
          User user = new User();

        user.setAddress("上海");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setUsername("富媒體");
        user.setId(28);
        int i= sqlSession.update("test.updateUserById",user);
        sqlSession.commit();
        */
        /*
           int i= sqlSession.delete("test.deleteUserById",28);
        sqlSession.commit();
        */
    }
  

封裝dao調(diào)用getMapper方法

public interface UserMapper {

    //遵循4個原則
    //接口名字==User.xml中的id
    //返回類型與Mapper.xml中的返回類型一直
    //方法的入?yún)⑴cMapper.xml的入?yún)⒁恢?    //命名空間綁定接口
    List<User> findUserByQueryVo(QueryVo vo);

    public Integer countUser();

}
<mapper namespace="com.fmt.mybatis.UserMapper">
 <select id="findUserByQueryVo" parameterType="com.fmt.mybatis.pojo.QueryVo" resultType="com.fmt.mybatis.pojo.User">
        select * from user where username like "%"#{user.username}"%";
    </select>

    <select id="countUser" resultType="Integer">
        SELECT count(*) from USER
    </select>
</mapper>
    @Test
    public void fun5() throws IOException {
//        加載核心配置文件
        String resource="sqlMapConfig.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        //創(chuàng)建sqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //創(chuàng)建sqlsession
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        QueryVo queryVo = new QueryVo();
        User user = new User();
        user.setUsername("五");
        queryVo.setUser(user);
        List<User> userByQueryVo = mapper.findUserByQueryVo(queryVo);
        for (User u:userByQueryVo){
            System.out.println(u);
        }
        System.out.println(mapper.countUser());
    }

如果數(shù)據(jù)庫字段與對象中的字段不一致使用resultmap來處理


    <resultMap id="orders" type="com.fmt.mybatis.pojo.Orders">
        <!--數(shù)據(jù)庫字段與java對象中不同的字段映射-->
        <result column="user_id" property="userId"/>
    </resultMap>
    <!--這里是resultMap 之前是resultType-->
    <select id="selectOrderList" resultMap="orders">
        SELECT id,user_id,number,createtime,note FROM  orders
    </select>

動態(tài)sql

  • if/where
    <!--where 標簽 可以去掉第一個前And-->
<select id="selectUserBySexAndUserName" parameterType="com.fmt.mybatis.pojo.User" resultType="com.fmt.mybatis.pojo.User">
        select * from user
        <where>
            <if test="sex!=null and sex!=''">
                sex=#{sex}
            </if>
            <if test="username!=null and username!=''">
                and username =#{username}
                
            </if>
        </where>

    </select>

別把and放后面 比如 username=#{username} and

    User user = new User();
//        user.setSex("1");
        user.setUsername("張小明");
        List<User> users = mapper.selectUserBySexAndUserName(user);
        for (User or:users){
            System.out.println(or);
        }
  • sql片段:提取公共是sql語句
  <sql id="selector">
        SELECT * FROM  user
    </sql>
    <select id="selectuser" parameterType="com.fmt.mybatis.pojo.User" resultType="com.fmt.mybatis.pojo.User">
        <include refid="selector"/>
        <where>
            <if test="sex!=null and sex!=''">
                sex=#{sex}
            </if>
            <if test="username!=null and username!=''">
                and username =#{username}

            </if>
        </where>

    </select>
  • foreach

 <!--多個Id(1,2,3)-->
    <!--<select id="selectUserByIds" parameterType="com.fmt.mybatis.pojo.QueryVo" resultType="com.fmt.mybatis.pojo.User">-->
        <!--<include refid="selector"></include>-->
        <!--<where>-->
            <!--id IN -->
            <!--<foreach collection="list_ids" item="id" separator="," open="(" close=")">-->
                <!--#{id}-->
            <!--</foreach>-->
        <!--</where>-->
    <!--</select>-->
   <!--此處的array是傳入integer[]數(shù)組-->
    <select id="selectUserByIds" parameterType="com.fmt.mybatis.pojo.QueryVo" resultType="com.fmt.mybatis.pojo.User">
        <include refid="selector"></include>
        <where>
            id IN
            <foreach collection="array" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        </where>
    </select>
 QueryVo queryVo = new QueryVo();
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(24);
        integers.add(22);
        queryVo.setList_ids(integers);

        List<User> users = mapper.selectUserByIds(queryVo);

 Integer[] integers=new Integer[2];
        integers[0]=24;
        integers[1]=22;
     List<User> users = mapper.selectUserByIds(integers);
        for (User or:users){
            System.out.println(or);
        }

一對一關(guān)聯(lián)

    <!--一對一關(guān)聯(lián)-->
    <resultMap type="com.fmt.mybatis.pojo.Orders" id="order">
        <result column="id" property="id"/>
        <result column="user_id" property="userId"/>
        <result column="number" property="number"/>
        <!-- 一對一 Order對象內(nèi)部有個user成員變量-->
        <association property="user" javaType="com.fmt.mybatis.pojo.User">
            <id column="user_id" property="id"/>
            <result column="username" property="username"/>
        </association>
    </resultMap>
    <select id="selectOrders" resultMap="order">
        SELECT
        o.id,
        o.user_id,
        o.number,
        o.createtime,
        u.username
        FROM orders o
        left join user u
        on o.user_id = u.id
    </select>
  List<Orders> selectOrdersList = mapper.selectOrders();

        for (Orders orders : selectOrdersList) {
            System.out.println(orders);
        }

一對多

    <!--一對多-->
    <resultMap type="com.fmt.mybatis.pojo.User" id="user">
        <id column="user_id" property="id"/>
        <result column="username" property="username"/>
        <!-- 一對多用戶里面有訂單集合對象 -->
        <collection property="ordersList" ofType="com.fmt.mybatis.pojo.Orders">
            <id column="id" property="id"/>
            <result column="number" property="number"/>
        </collection>
    </resultMap>
    <select id="selectUserList" resultMap="user">
        SELECT
        o.id,
        o.user_id,
        o.number,
        o.createtime,
        u.username
        FROM user u
        left join orders o
        on o.user_id = u.id
    </select>

spring與mybatis結(jié)合

sqlMapConfig.xml

<?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>
        <!-- 2. 指定掃描包,會把包內(nèi)所有的類都設置別名,別名的名稱就是類名坞古,大小寫不敏感 -->
        <package name="com.fmt.springmybatis" />
    </typeAliases>

    <mappers>
        <package name="com.fmt.springmybatis"/>
    </mappers>

</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    <context:property-placeholder location="classpath:db.properties"/>
    
    <!-- 數(shù)據(jù)庫連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>
    
    <!-- Mybatis的工廠 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 核心配置文件的位置 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    </bean>


    <!--原始dao-->
    <!--<bean id="userDao" class="com.fmt.springmybatis.dao.UserDaoImp">-->
        <!--<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>-->
    <!--</bean>-->

    <!--Mapper動態(tài)代理開發(fā)-->
     <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
         <!--<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>-->
         <!--<property name="mapperInterface" value="com.fmt.springmybatis.map.UserMap"></property>-->
     <!--</bean>-->

    <!--Mapper掃描基本包 掃描-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--基本包-->
        <property name="basePackage" value="com.fmt.springmybatis.map"></property>
    </bean>
</beans>
public class test {
    @Test
    public void test(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //這是mapper動態(tài)代理
//        UserMap userMapper = (UserMap) ac.getBean("userMapper");
//這是Mapper掃描基本包
        UserMap userMap=ac.getBean(UserMap.class);
        User userById = userMap.findUserById(10);
        System.out.print(userById);
    }
}

mybatis 逆向工程(mybaits需要程序員自己編寫sql語句,mybatis官方提供逆向工程,可以針對單表自動生成mybatis執(zhí)行所需要的代碼)

http://blog.csdn.net/h3243212/article/details/50778937

mybatis與hibernate的不同

Mybatis不完全是ORM框架伴找, 因為Mybatis需要程序員自己寫sql預計稻轨,程序員直接編寫原生態(tài)sql徒坡,可嚴格控制sql執(zhí)行性能羞酗,靈活度高,但是mybatis無法做到數(shù)據(jù)庫無關(guān)性(如果換數(shù)據(jù)庫sql需要重寫)无蜂,hibernate數(shù)據(jù)無關(guān)性強

別人總結(jié)很具體:http://www.cnblogs.com/inspurhaitian/p/4647485.html

參考文章http://www.cnblogs.com/inspurhaitian/p/4647485.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末伺糠,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子斥季,更是在濱河造成了極大的恐慌训桶,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酣倾,死亡現(xiàn)場離奇詭異舵揭,居然都是意外死亡,警方通過查閱死者的電腦和手機躁锡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門琉朽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人稚铣,你說我怎么就攤上這事∈澹” “怎么了惕医?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長算色。 經(jīng)常有香客問我抬伺,道長,這世上最難降的妖魔是什么灾梦? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任峡钓,我火速辦了婚禮妓笙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘能岩。我一直安慰自己寞宫,他們只是感情好,可當我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布拉鹃。 她就那樣靜靜地躺著辈赋,像睡著了一般。 火紅的嫁衣襯著肌膚如雪膏燕。 梳的紋絲不亂的頭發(fā)上钥屈,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天,我揣著相機與錄音坝辫,去河邊找鬼篷就。 笑死,一個胖子當著我的面吹牛近忙,可吹牛的內(nèi)容都是我干的竭业。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼银锻,長吁一口氣:“原來是場噩夢啊……” “哼永品!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起击纬,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鼎姐,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后更振,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體炕桨,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年肯腕,在試婚紗的時候發(fā)現(xiàn)自己被綠了献宫。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡实撒,死狀恐怖姊途,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情知态,我是刑警寧澤捷兰,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站负敏,受9級特大地震影響贡茅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一顶考、第九天 我趴在偏房一處隱蔽的房頂上張望赁还。 院中可真熱鬧,春花似錦驹沿、人聲如沸艘策。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽柬焕。三九已至,卻和暖如春梭域,著一層夾襖步出監(jiān)牢的瞬間斑举,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工病涨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留富玷,地道東北人。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓既穆,卻偏偏與公主長得像赎懦,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子幻工,可洞房花燭夜當晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 每個線程都應該有它自己的SqlSession實例励两。SqlSession的實例不能共享使用,它是線程不安全的 配置文...
    蕊er閱讀 474評論 0 0
  • 1. 簡介 1.1 什么是 MyBatis 囊颅? MyBatis 是支持定制化 SQL当悔、存儲過程以及高級映射的優(yōu)秀的...
    笨鳥慢飛閱讀 5,520評論 0 4
  • 一盲憎、輸入映射 通過parameterType指定輸入?yún)?shù)的類型,類型可以是簡單類型胳挎、HashMap饼疙、pojo的包裝...
    yjaal閱讀 953評論 0 2
  • 一生太長,能步履輕松慕爬,絕不蹣跚前行窑眯。 學會放下更多不快,才能裝進更多幸福医窿。 人身非鋼板伸但,多些滋養(yǎng),少些硬撐留搔,方能爭...
    nataliev閱讀 358評論 0 0
  • (一) 飄飄那片樹葉 為何不忍落下 戀樹枝 像戀自己的家嗎? 落下吧 為了明年的枝繁葉茂 許多時候 愛是默默的肥料...
    水青石閱讀 244評論 0 3