mybatis学习

1.什么是Mybatis?

是一个支持SQL查询,存储以及高级映射的持久层框架,消除了几乎所有JDBC代码和参数的手动配置,只需要XML或注解进行配置和原始映射.

2.Mybatis的工作原理

要我们理解工作原理,首先我们通过一个例子再总结.首先这个是demo的目录

下面的代码知识点有哪些呢:mybatis的工作原理,mybatis的核心类和核心配置,动态SQL,Junit测试单元

 

(1)首先创建数据库mybatis,和对应的表,并填下数据

(2)创建一个web项目,在lib中导入mybatis需要的环境jar包

(3)在src目录下创建log4j.properties文件,用于查看控制台中的SQL语句(这个内容不需要手打,在mybatis的使用手册中找到复制就好)

(4)在po包下创建一个Customer类,属性对应之前的表的属性

(5)在mapper包下创建映射文件CustomerMapper.xml,这些都是SQL操作

<?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.itheima.mapper.CustomerMapper">
<select id="findCustomerById"  parameterType="Integer"  resultType="com.itheima.po.Customer">
select * from t_customer where id = #{id}
</select>

<insert id="addCustomer" parameterType="com.itheima.po.Customer">
    insert into t_customer(username,jobs,phone) values(#{username},#{jobs},#{phone})
</insert>

<!-- 下面是动态SQL文件操作演示 -->
<!-- <if>元素使用 -->
<select id="findCustomerByNameAndJobs" parameterType="com.itheima.po.Customer" resultType="com.itheima.po.Customer">
<bind name="pattern_name" value="'%'+_parameter.getUsername()+'%'"/><!-- <bind>解决不同数据库厂商的模糊查询的共性方法 -->
    select * from t_customer where 1=1
    <if test="username!=null and username!=''">
        and username like #{pattern_name}
    </if>
    <if test="jobs!=null and jobs!=''">
        and jobs=#{jobs}
    </if>
</select>

<!-- <choose>(<when>,<otherwise>元素使用) 等效于swtich case-->
<select id="findCustomerByNameOrJobs" parameterType="com.itheima.po.Customer" resultType="com.itheima.po.Customer">
    select * from t_customer
    <where>
    <choose>
        <when test="username!=null and username!=''">
            and username like concat('%',#{username},'%')
        </when>
        <when test="jobs!=null and jobs!=''">
            and jobs=#{jobs}
        </when>
        <otherwise>
            and phone is not null
        </otherwise>
    </choose>
    </where>
</select>

<!-- <set>元素使用,一般用于更新操作 -->
<update id="updateCustomer" parameterType="com.itheima.po.Customer">
update t_customer
    <set>
        <if test="username!=null and username!=''">
            username=#{username},
        </if>
        <if test="jobs!=null and jobs!=''">
            jobs=#{jobs},
        </if>
        <if test="phone!=null and phone!=''">
            phone=#{phone},
        </if>
    </set>
where id=#{id}
</update>


</mapper>
View Code

(6)在src目录下创建mybatis核心配置文件mybatis-config.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>
  <properties resource="db.properties"/>
   <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 将我们写好的sql映射文件一定要注册到全局配置文件中 -->
  <mappers>
    <mapper resource="com/itheima/mapper/CustomerMapper.xml"/>
  </mappers>
</configuration>
View Code

为了实现jdbc数据与xml链接数据库的结构的分离,所以我们用db.properties

(7)下面在util创建一个mybatisUtils工具类,他的作用是什么呢?

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
    private static String resource="mybatis-config.xml";
    //初始化SqlSessionFactory的对象
    static{
        try{
            InputStream inputstream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputstream);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}
View Code

这个工具类用于读取mybatis-config.xml的配置信息,并且创建sqlSessionFactory然后创建SQLSession对象,只有通过这个对象才能进行有关mapper里面的数据库操作

(8)下面写测试类

package com.itheima.test;
/**
 * 知识点包括:动态SQL,mybatis核心配置,mybatis入门与工作原理
 */
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.itheima.po.Customer;
import com.itheima.utils.MybatisUtils;

public class MybatisTest {
    
    @Test
    public void findCustomerByIdTest() throws Exception{
        SqlSession sqlSession = MybatisUtils.getSession();
        //4.SqlSession执行映射文件中定义的SQL,并返回映结果
        Customer customer = sqlSession.selectOne("com.itheima.mapper"+".CustomerMapper.findCustomerById",1);
        //打印输出的结果
        System.out.println(customer.toString());
        sqlSession.close();
    }
    
    @Test
    public void findCustomerByNameAnd_ORJobsTest(){
        SqlSession sqlSession = MybatisUtils.getSession();
        Customer c = new Customer();
        c.setUsername("jack");c.setJobs("teacher");//要查询的信息
        //ִ执行sqlSession方法,并返回结果集
        List<Customer> customers = sqlSession.selectList("com.itheima.mapper"
        +".CustomerMapper.findCustomerByNameAndJobs",c);
        for(Customer customers2:customers){
            System.out.println(customers2);
        }
        sqlSession.close();
    }
    
    @Test
    public void update(){
        SqlSession sqlSession = MybatisUtils.getSession();
        Customer c = new Customer();
        c.setId(3);c.setPhone("2333333333");
        int row = sqlSession.update("com.itheima.mapper"
        +".CustomerMapper.updateCustomer",c);
        if(row>0)
            System.out.println("成功修改"+row+"条数据");
        else
            System.out.println("操作失败");
        sqlSession.commit();sqlSession.close();
    }
    
    @Test
    public void add() throws Exception{
        //1.读取配置文件
        String resource="mybatis-config.xml";
        InputStream inputstream = Resources.getResourceAsStream(resource);
        //2.根据配置文件创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputstream);
        //3.ͨ通过SqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.SqlSession执行添加操作
        Customer c = new Customer();
        c.setUsername("pppp");c.setJobs("student");c.setPhone("168168168");
        int row = sqlSession.insert("com.itheima.mapper"+".CustomerMapper.addCustomer",c);
        if(row>0)
            System.out.println("你成功插入"+row+"条数据");
        else
            System.out.println("error,操作失败");
        sqlSession.commit();
        sqlSession.close();
    }
}
View Code

 好了上面就是所有代码的内容

现在我们来总结下mybatis的工作流程:

1.收先读取mybatis-config.xml和核心配置文件,这里面包含数据源和需要执行SQL操作的mapper文件.

2.读取后创建SQLSessionFactory工厂对象

3.通过这个工厂对象SQLSession会话对象,这里面有执行器Executot,通过这个对象才能执行配置文件中mapper文件对应的SQL操作

4.返回结果输出映射,返回的数据类型可以使pojos,集合型,基本数据型

原文地址:https://www.cnblogs.com/zoulingjin/p/9590895.html