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" />
            <!-- 数据库连接池 -->
            <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">
         <!-- 添加用户返回调用获取最后插入的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);
        //创建sqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //创建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调用getMapper方法

public interface UserMapper {

    //遵循4个原则
    //接口名字==User.xml中的id
    //返回类型与Mapper.xml中的返回类型一直
    //方法的入参与Mapper.xml的入参一致
    //命名空间绑定接口
    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);
        //创建sqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //创建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());
    }

如果数据库字段与对象中的字段不一致使用resultmap来处理


    <resultMap id="orders" type="com.fmt.mybatis.pojo.Orders">
        <!--数据库字段与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>

动态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[]数组-->
    <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);
        }

一对一关联

    <!--一对一关联-->
    <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对象内部有个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结合

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. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
        <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"/>
    
    <!-- 数据库连接池 -->
    <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动态代理开发-->
     <!--<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动态代理
//        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执行所需要的代码)

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

mybatis与hibernate的不同

Mybatis不完全是ORM框架, 因为Mybatis需要程序员自己写sql预计,程序员直接编写原生态sql,可严格控制sql执行性能,灵活度高,但是mybatis无法做到数据库无关性(如果换数据库sql需要重写),hibernate数据无关性强

别人总结很具体:http://www.cnblogs.com/inspurhaitian/p/4647485.html

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容

  • 每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能共享使用,它是线程不安全的 配置文...
    蕊er阅读 456评论 0 0
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,288评论 0 4
  • 一、输入映射 通过parameterType指定输入参数的类型,类型可以是简单类型、HashMap、pojo的包装...
    yjaal阅读 919评论 0 2
  • 一生太长,能步履轻松,绝不蹒跚前行。 学会放下更多不快,才能装进更多幸福。 人身非钢板,多些滋养,少些硬撑,方能争...
    nataliev阅读 342评论 0 0
  • (一) 飘飘那片树叶 为何不忍落下 恋树枝 像恋自己的家吗? 落下吧 为了明年的枝繁叶茂 许多时候 爱是默默的肥料...
    水青石阅读 228评论 0 3