MyBatis使用

简书链接:http://www.jianshu.com/p/9803529e7c1e
####导包

  • 下载mybaits https://github.com/mybatis/mybatis-3/releases
  • 下载连接mysql驱动

配置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.youkuaiyun.com/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值