Mybatis(一)

1.MyBatis简介

作用:封装了JDBC操作,简化数据库访问代码
封装功能如下:
①–封装了获取连接,执行SQL,释放连接
②–封装了SQL参数设置

insert into emp(name,age) values(?,?)  
---->
insert into emp (name,age) values (#{name},#{age})

③–封装了记录映射成实体对象过程
(实体类属性名与查询结果集ResultSet中列名保持一致)

2. 流程

未整合spring的mybatis

①src/SqlMapConfig.xml主配置文件,整合spring后,就在spring的配置中配
②entity(POJO)
③xml中配sql(通常给每个xml还写一个接口,不写也不会错)

主配置

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE configuration             
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" 
      "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">

<!-- 配置环境变量 --> 
<configuration>
    <environments default="environment">
        <environment id="environment">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" 
                    value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql:///javaweb?useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <!-- 配置mappers,即加载SQL定义文件 -->

    <mappers>
        <mapper resource="cn/whbing/mybatis/entity/EmpSqlMapper.xml" />
    </mappers>

</configuration> 

entity

public class Emp implements Serializable{
    private Integer id;
    private String name;
    private Double salary;
    private Integer age;
    ... ...

mapper ( EmpSqlMapper.xml )

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="cn.whbing.mybatis.entity.EmpSqlMapper">

    <select id="findAll" 
        resultType="cn.whbing.mybatis.entity.Emp">
        select * from emp
    </select>

    <select id="findLikeName" 
        parameterType="string"
        resultType="cn.whbing.mybatis.entity.Emp">
        select * from emp 
        where name like #{name}
    </select>

    <select id="findById" parameterType="int"
        resultType="cn.whbing.mybatis.entity.Emp">
        select * from emp 
        where id=#{id}
    </select>

    <insert id="save" parameterType="cn.whbing.mybatis.entity.Emp">
        insert into emp(name,salary,age) values (#{name},#{salary},#{age})----①
    </insert>

    <delete id="delete" parameterType="int">
        delete from emp where id=#{eid}
    </delete>

    <update id="updateSalary" parameterType="cn.whbing.mybatis.entity.Emp">
        update emp set salary=#{salary} where id=#{id}
    </update>


</mapper>

注:多参数时,如①,#{}中的内容和实体类字段一样。

测试

通过SqlSessionFactoryBuilder获得SqlSessionFactory再获得SqlSession的过程,我们可以将其单独写成工具类(单例模式),然后获取session操作。

public class MyBatisUtil {
    public static SqlSession getSqlSession(){
        String resource = "SqlMapConfig.xml";
        //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is = TestEmp.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //获取SqlSession
        SqlSession session = factory.openSession();
        return session;
    }
}
public class TestEmp {
    public static void main(String[] args) throws IOException {
        SqlSession session = MyBatisUtil.getSqlSession();
        List<Emp> list =session.selectList("findAll");
        for (Emp emp : list) {
            System.out.println(emp.getName());
        }
        Emp emp2=session.selectOne("findById",12);
        System.out.println(emp2.getName());
        List<Emp> list3=session.selectList("findLikeName","%志%");
        for (Emp emp3 : list3) {
            System.out.println(emp3.getName());
        }
        ... ...

改进

  1. 若只需要实体中很多字段的很少个字段,封装成实体类会导致很多字段为空。
    可以封装成map
    CostMapper.xml:
    <select id="findMap" resultType="map">
        select cost_id,name from cost 
    </select>

测试:

List<Map<String,Object>> list=session.selectList("findMap");
for (Map<String, Object> map : list) {               
    System.out.println(map.get("cost_id")+":"+map.get("name"));
}

进阶:Mapper映射器接口规则

1.返回数据类型
–实体对象
–Map集合
–基本值

2.Mapper映射器接口规则
a.根据SQL定义的id属性当接口方法名
b.根据SQL定义的parameterType类型当方法参数类型
c.根据SQL定义的resultType类型定义方法返回类型
  (多行使用List<泛型>; 单行使用泛型)
d.将SQL定义文件的namespace属性指定成包名.接口名

1.CostMapper.xml

这里写图片描述
1.DAO接口
这里写图片描述

3.说明:为什么接口和xml对应起来呢?

相当于xml中的操作是对接口的实现方法。Xml相当于给我们做了实现类。那么如何获得这个对象呢?
CostDao costDao=session.getMapper(CostDao.class);
System.out.println(costDao.getClass());
结果:class com.sun.proxy.$Proxy0
Proxy0就相当于实现类。
接下来就可以用实例调用方法,如costDao.findAll();

4.测试使用映射器接口后的方法:

costDao=session.getMapper(CostDao.class);
List list=costDao.findAll();
for (Cost cost : list) {
System.out.println(cost.getName());
}

2. 整合spring的mybatis

spring.xml的配置(直接在spring的注配置中配)

<!-- 要获得mapper(及接口)和Sqlsession才可以得到dao的对象 -->
<bean id="costDao"class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="cn.whbing.dao.CostDao"></property>
    <property name="sqlSessionFactory" ref="ssf"></property>
</bean>   

<!-- 创建sqlsessionfacory -->
<beanid="ssf"class="org.mybatis.spring.SqlSessionFactoryBean">
    <propertyname="dataSource"ref="dbcp"></property>
    <propertyname="mapperLocations"value="classpath:cn/whbing/sql/*.xml"></property>
</bean>

<!-- 定义dbcp的DataSource -->
<beanid="dbcp"
    class="org.apache.commons.dbcp.BasicDataSource">
    <property name="username"value="root">
    </property>
    <property name="password"value="root">
    </property>
    <property name="url"
    value="jdbc:mysql:///javaweb?useUnicode=true&amp;characterEncoding=utf8">
    </property>
    <property name="driverClassName"
       value="com.mysql.jdbc.Driver">
    </property>
</bean>
说明:上述第二步中加载了mybatis每个表的xml,相当于完成了mybatis的主配置xml文件。因此不再需要mybatis主配置xml文件。

测试:

public class CostDaoTest {
   public staticvoid main(String[] args) {
      ApplicationContext ac= new ClassPathXmlApplicationContext("spring.xml");
      CostDao costDao=ac.getBean("costDao",CostDao.class);
      List<Cost> list=costDao.findAll();
      for (Cost cost : list) {
         System.out.println(cost.getName());
      }
   }
}

原理

http://blog.csdn.net/hupanfeng/article/details/9068003/

http://www.cnblogs.com/caiguoqing/p/6889394.html

http://blog.csdn.net/ykzhen2015/article/details/50315027

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值