---
title: "Mybatis菜鸟自学（二）"
author: "心跳停了"
date: "2015-05-28T19:58:30Z"
tags: []
categories: ["编程语言"]
slug: "mybatis"
draft: false
lastmod: "2015-08-21T14:17:41Z"
id: 2215201
url: "https://yangcaijun.iteye.com/blog/2215201"
---

mybaits几大核心对象生命周期以及crud

一、mybatis几大对象的生命周期

1、SqlSessionFactryBuilder ：这个对象只是用于创建SqlSessionFatory，只要                    SqlSessionFactory创建成功，则自动销毁

2、SqlSessionFactory:整个应用执行期间都一直存在；通常使用单例形式

3、sqlSession: 每一个线程都应该有单独的独立的sqlSession ，相互之间不受影响，必      须保证每一个SqlSession是一个线程独立拥有的，所以我们一般都是在finally中关   闭；否则可能导致内存溢出

二、Mybatis的Mapper.xml文件的标签（select，insert，update，delete）上的属性，以下仅   列举了常用的：

id ：为命名空间唯一标示，可以用来引用该对应标签下的sql语句

parameterType :定义该标签下sql语句中传入的参数对应的类名或者权限定名

resultType：数据库查询出的数据封装成期望对象的权限定名或者别名，如果为集合，                   则是集合中元素类型

statementType：可以拥有3个值（STATEMENT，PREPARED，CALLABLE），对应jdbc                      中特殊的语句类

                           STATEMENT：最简单的sql，就是直接在等号右边写具体值的

                           PREPARED：预编译的sql通常是一占位符传参的方式

                           CALLABLE：通常指调用存储过程的形式等复杂处理  

flushCache:为是否缓存标签下的sql模板，如果为true每次执行都会清除该模板sql，为                      fasle则把sql模板缓存起来，默认false

timeout：超时，定义驱动程序等待数据库放回请求结果，如果时间超过指定值，则抛                 出异常

userGeneratedKeys:仅仅对insert有效，使用自动生成的键，会让mybatis调用                               getGeneratedKes方法取出数据新增的id，仅针对数据库的主键有自增功能方                  可使用

 

三、别名的设置

在我们parameterType ，resultType这两个属性中，我们可以设置传入或者返回对象类型，一般情况我们都是用权限定类名，但是权限定类名过于复杂，我们就可以设置别名

别名的标签&lt;typeAliases&gt;&lt;/typeAliases&gt; 和&lt;typeAlias/&gt;

方式如下：

&lt;typeAliases&gt;

       &lt;typeAlias alias="别名" type="对应类的全类名"/&gt;

&lt;/typeAliases&gt;

 

例如：

Mapper中原来的配置：

&lt;update id=*"updateEmployee"*                parameterType=*"cn.ycj.mybatis.domain.Employee"*&gt;

      update Employee set name=#{name},password=#{password} where id=#{id}

   &lt;/update&gt;

配置别名

&lt;typeAliases&gt;

         &lt;typeAlias  alias=*"Employee"*  type=*"cn.ycj.mybatis.domain.Employee"*/&gt;

   &lt;/typeAliases&gt;

 

配置别名后的配置

&lt;update id=*"updateEmployee"*              parameterType=*"Employee"*&gt;

      update Employee set name=#{name},password=#{password} where id=#{id}

   &lt;/update&gt;

  

    

四、 Mybatis使用步骤：

1、加载配置文件，创建SqlSessionFactory

2.、获取会话 SqlSession

3、操作以及提交事务

4、关闭会话

 

五、做一个Employee的CRUD

1、创建一个Employee类，提供相应的构造方法和getter ，setter，toString方法

**publicclass** Employee {

   **private** Long id;

   **private** String name;

   **private** String password;

   **public** Employee() {

      **super**();

   }

   **public** Employee(String name, String password) {

      **super**();

      **this**.name = name;

      **this**.password = password;

   }

   **public** Long getId() {

      **return**id;

   }

   **publicvoid** setId(Long id) {

      **this**.id = id;

   }

   **public** String getName() {

      **return**name;

   }

   **publicvoid** setName(String name) {

      **this**.name = name;

   }

   **public** String getPassword() {

      **return**password;

   }

   **publicvoid** setPassword(String password) {

      **this**.password = password;

   }

   @Override

   **public** String toString() {

      **return**"Employee [id=" + id + ", name=" + name + ", password="

            + password + "]";

   }

  

  

}

2、创建mybatis的配置文件mybatis-config.xml和Employee的映射文件EmployeeMapper文件，mapper中先为空白，做一个加一个配置文件

mybatis-config.xml内容：

&lt;configuration&gt;

   &lt;typeAliases&gt;

      &lt;typeAlias  alias=*"Employee"* type=*"cn.ycj.mybatis.domain.Employee"*/&gt;

   &lt;/typeAliases&gt;

   &lt;environments default=*"development"*&gt;

      &lt;environment id=*"development"*&gt;

         &lt;transactionManager type=*"JDBC"* /&gt;

         &lt;dataSource type=*"POOLED"*&gt;

            &lt;property name=*"driver"* value=*"com.mysql.jdbc.Driver"* /&gt;

            &lt;property name=*"url"* value=*"jdbc:mysql://localhost:3306/mybatis?createDatabaseIfNotExist=true"* /&gt;

            &lt;property name=*"username"* value=*"root"* /&gt;

            &lt;property name=*"password"* value=*"admin"* /&gt;

         &lt;/dataSource&gt;

      &lt;/environment&gt;

   &lt;/environments&gt;

   &lt;mappers&gt;

      &lt;mapper resource=*"cn/ycj/mybatis/domain/EmployeeMapper.xml"* /&gt;

   &lt;/mappers&gt;

&lt;/configuration&gt;

 

 

 

EmployeeMapper.xml的内容

&lt;?xml version=*"1.0"* encoding=*"UTF-8"*?&gt;

&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;

 

&lt;mapper namespace=*"org.mybatis.example.EmployeeMapper"*&gt;

  

&lt;/mapper&gt;

 

3、创建一个junit的EmployeeDao测试类，先为空白，做一个方法加一个方法

**package** cn.ycj.mybatis.dao;

**publicclass** EmployeeDaoTest {

  

}

 

 

4、做一个单例模式的mybatis的工具

因SqlSessionFactoryBuilder，SqlSessionFactory整个活动中只需要使用一个，所以可以创建一个静态类来获取一个通用的，但是session不能是通用，故提供一个获取session的方法，每次都获得新的session，类如下：

**publicclass** MybatisUtils {

   **privatestatic** SqlSessionFactory *sessionFactory*;

   **static** {

      **try** {

         Reader reader = Resources.*getResourceAsReader*("mybatis-config.xml");

         *sessionFactory* = **new** SqlSessionFactoryBuilder().build(reader);

      } **catch** (IOException e) {

         e.printStackTrace();

      }

   }

   **publicstatic** SqlSession getSession() {

      **returnsessionFactory**.openSession();

   }

}

 

 

5、在mysql（大家可以是用自己常用的数据库），建立employee表

6、执行添加数据操作

在配置文件中做一条插入数据的配置

&lt;insert id=*"insertEmp"* parameterType=*"Employee"* &gt;

      insert into employee(name,password) values(#{name},#{password})

   &lt;/insert&gt;

传入的时一个Emloyee对象，设置的时候对字段则为#{Employee对应的属性}

在EmployeeDao中写测试代码执行操作

@Test

   **publicvoid** save() **throws** Exception {

      SqlSession session = MybatisUtils.*getSession*();

      Employee emp=**new** Employee("yc", "222");

      session.insert("insertEmp", emp);

      session.commit();

      session.close();

   }

这里可以发现，用openSession()打开的session的事物需要自己手动提交

 

7、查询一条数据

Mapper文件添加如下配置，记得做Employee的别名

&lt;select id=*"selectEmp"* parameterType=*"Long"* resultType=*"Employee"*&gt;

      select * from Employee where id=#{id}

   &lt;/select&gt;

在EmployeeDao中写测试代码执行操作

@Test

   **publicvoid** get() **throws** Exception {

      SqlSession session = MybatisUtils.*getSession*();

      Employee emp=session.selectOne("selectEmp", 2L);//这里不用强转换，mybatis会自动封装

session.close();

      System.***out***.println(emp);

   }

 

 

 

8、查询所有数据

Mapper文件添加如下配置，

&lt;select id=*"findAll"* resultType=*"Employee"*&gt;

         select * from Employee

   &lt;/select&gt;

在EmployeeDao中写测试代码执行操作  

@Test

   **publicvoid** getAll() **throws** Exception {

      SqlSession session = MybatisUtils.*getSession*();

      List&lt;Employee&gt; emps=session.selectList("findAll");//这里不用强转换，mybatis会自动封装

      session.close();

      System.***out***.println(emps);

   }

 

9、删除一条数据

 

Mapper文件添加如下配置，

&lt;delete id=*"deleteEmp"* parameterType=*"Long"*&gt;

      delete from employee where id=#{id};

   &lt;/delete&gt;

 

在EmployeeDao中写测试代码执行操作

@Test

   **publicvoid** delete() **throws** Exception {

      SqlSession session = MybatisUtils.*getSession*();

      session.delete("deleteEmp",2L);

      session.commit();

      session.close();

  

   }