Mybatis框架学习(一)

一、环境搭建

1.jar包的下载

https://github.com/mybatis/mybatis-3/releases
从里面下载对应的zip压缩包
然后在lib目录下添加
log4j.jar和mysql-connector-java-5.1.37-bin.jar
可以从
https://mvnrepository.com/
进行对应的下载。

2.文件的配置

在这里插入图片描述
创建一个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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe"/>
                <property name="username" value="SYSTEM"/>
                <property name="password" value="1"/>
            </dataSource>
        </environment>
    </environments>
    <!--<mappers>-->
    <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
<!--</mappers>-->
</configuration>

然后就可以开始写代码了

二、入门

1.书写第一个程序

首先我们从官方文档入手
***2.1.2 Building SqlSessionFactory from XML通过xml的方式创建SqlSessionFactory
意思是,利用xml的方式创建一个SqlSessionFactory,并且给了样例代码

String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"development");
        System.out.println(sqlSessionFactory);

这个xml主要是对mybatis的主要配置,上文贴出了配置好的代码。


在这里插入图片描述
而这个是不通过xml的方式去配置SqlSessionFactory


在这里插入图片描述
后面又介绍了通过SqlSessionFactory创建SqlSession,目的就是使用SqlSession去执行sql命令操作数据库

SqlSession sqlSession = sqlSessionFactory.openSession();

文档又在创建SqlSession之后执行了一个搜索操作

try {
  Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
 } finally 
{
  session.close();
   }

主要来看一下session.selectOne,第一个参数的意思是使用一个唯一标识符匹配
第二个参数的意思是,执行sql语句需要用到的参数对象


在这里插入图片描述
接下来就是sql语句的映射文件了
将之前在mybatis-config的注释去除,然后把Mapper文件配置上就可以了

<mappers>
        <mapper resource="EmployeeMapper.xml"/>
    </mappers>

而程序的执行顺序就是:
1.String resource="mybatis-config.xml"然后从下面去自动匹配到了这个xml文件
2.再由这个文件找到了Mapper文件,从mapper文件中又找到了由id对应的唯一匹配的sql语句

<select id="selectEmployee" resultType="beans.Employee">

3.然后执行对应的sql


下面来贴一下我的代码
测试代码:

public class TestMybatis {
    @Test
    public void testSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"development");
        System.out.println(sqlSessionFactory);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            Employee employee = sqlSession.selectOne("Emp.selectEmployee", 1);
            System.out.println(employee);
        }catch (Exception e){}
        finally {
            sqlSession.close();
        }
    }
}

这是表的数据
在这里插入图片描述
对应的get set方法的类Employee

public class Employee {
    private String isbn;
    private String bookName;
    private Integer price;

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "isbn='" + isbn + '\'' +
                ", bookName='" + bookName + '\'' +
                ", price=" + price +
                '}';
    }
}

测试程序输出结果:

org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@458c1321
DEBUG 01-26 16:56:16,290 ==>  Preparing: select * from BOOK1 where price = ?   (BaseJdbcLogger.java:145) 
DEBUG 01-26 16:56:16,382 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 01-26 16:56:16,424 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{isbn='ISBN-001', bookName='null', price=1}

之所以,输出的bookName为null,是因为在数据库中的书名,是book_Name,所以原来的查询语句,就要改为

select isbn,book_Name bookName,price from book1 where price = #{price}

2.基于Mapper接口的crud操作

在mapper接口中写的方法,可以不用进行方法实现,这样就相对麻烦了,可是我们需要的是把每一个接口进行关联起来,成为真正的mapper接口开发,所以我们需要两个绑定操作。

    @Test
   public void testSqlSessionMapper() throws IOException {
       String resouce = "mybatis-config.xml";
       InputStream inputStream = Resources.getResourceAsStream(resouce);
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, "development");

       SqlSession sqlSession = sqlSessionFactory.openSession();
       try {
           /**
            * 两个绑定操作:
            * 1.每一个接口的实现都对应一个sql语句
            * 所以第一个绑定就是让方法与Mapper.xml文件的sql语句进行绑定
            * 最终完成crud操作
            *
            * sql语句的id值必须指定成为方法名
            * 2.方法存在于接口,sql存在于xml文件,所以第二个绑定就是
            * 让xml文件和接口文件进行绑定
            *
            * 映射文件的namespace的值必须指定成接口的全类名
            */

           /**
            * 获取Mybatis为Mapper接口生成的代理是现对象
            */
           EmployeeDao dao = sqlSession.getMapper(EmployeeDao.class);
           Employee employee = dao.getEmployeeByPrice(1);
           System.out.println(employee);

       }catch (Exception e) {
           e.printStackTrace();
       }finally {
           sqlSession.close();
       }
   }

    <!--    public Employee getEmployeeById(Integer id);-->
   <!--于此方法对应的sql语句-->
   <select id="getEmployeeByPrice" resultType="beans.Employee">
   select isbn,book_Name bookName,price from book1 where price = #{price}
   </select>
public interface EmployeeDao {
   //定义crud的相关方法

   //根据price查询Employee
   public Employee getEmployeeByPrice(Integer id);
   }

3.mybatis的全局配置文件

<1>properties

属性配置:
<property>:一个具体的属性配置
resource:引入类路径(src之类的子目录)下的属性文件
url:引入网络路径(某云盘)或者磁盘(本地)路径下的属性文件
在这里插入图片描述

<2>settings

<settings>
        <!--映射我们的下划线到驼峰命名
        也就是把我们第一个写的那个last_Name进行自动转换成lastName匹配-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

<3>typeAliases

在这里插入图片描述
可以使我们的一些命名变得更精简,比如需要写全类名的时候我们就可以用到了,当然这个alias也可以不写,因为在这种情况下,默认的就是类名。
在这里插入图片描述
同时也是支持批量进行精简化的,只需要指明包名就好。
而当包名重复的时候,可以在类上标明注解
在这里插入图片描述

<4>Environment

在这里插入图片描述
主要的作用是帮我们给很多不同的sql环境搭建出映射关系
并且可以帮我们指定在不同需求时候搭建不同的环境,而在开发,测试,上线的环境都是不相同的
这些都可以在default中指明
在这里插入图片描述


事务管理器:transactionManager
同时也是environments内所包含的其中一个属性,这个一般用来和spring结合起来使用
在这里插入图片描述


dataSource
分为POOLED和UNPOOLED两种,使用连接池和不使用连接池在这里插入图片描述
在这里插入图片描述
而dataSource也是交给springIOC完成

<5>mapper映射

我们之前说过
<mapper>:引入一个sql映射文件
resource:引入类路径下的sql映射文件
<package>:批量引入sql映射文件
直接在conf目录下new 一个package然后mapper下package属性引入包,就相当于引入了包内的全部sql映射文件了
注:
一般出现BindingException的话,一般就是在这里的mapper映射有些问题

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值