myBatis入门(二)-mybatis工作流程

来源:互联网 发布:数据库安全测试方法 编辑:程序博客网 时间:2024/05/16 09:07

myBatis工作流程

我们通过一个向数据库中插入一条数据记录的例子来了解一些myBatis的工作流程

  • 下面这个demo看下src下文件目录结构

这里写图片描述

  • 数据库表的描述如下,创建脚本很简单,这里就不写了
    这里写图片描述

下面开始写代码

第一步:写数据表对应的实体类Student.java

  package com.cxspace.bean;public class Student {    private int id;    private String s_name;    private int s_age;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getS_name() {        return s_name;    }    public void setS_name(String s_name) {        this.s_name = s_name;    }    public int getS_age() {        return s_age;    }    public void setS_age(int s_age) {        this.s_age = s_age;    }    @Override    public String toString() {        return "Student [id=" + id + ", s_name=" + s_name + ", s_age=" + s_age                + "]";    }    public Student(int id, String s_name, int s_age) {        super();        this.id = id;        this.s_name = s_name;        this.s_age = s_age;    }    public Student(){    }}

第二步:写实体类的映射配置文件StudentMapper.xml

<?xml version="1.0" encoding="UTF-8"?><!--       Copyright 2009-2012 the original author or authors.       Licensed under the Apache License, Version 2.0 (the "License");       you may not use this file except in compliance with the License.       You may obtain a copy of the License at          http://www.apache.org/licenses/LICENSE-2.0       Unless required by applicable law or agreed to in writing, software       distributed under the License is distributed on an "AS IS" BASIS,       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.       See the License for the specific language governing permissions and       limitations under the License.--><!DOCTYPE mapper    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--         namespace 用来保证唯一        命名习惯:包名 + sql映射配置文件名 --><mapper namespace="com.cxspace.bean.Student">  <!--         resultMap标签:映射实体与表        type属性:表示实体全路径名        id属性:为实体与表的映射取一个任意唯一的编号   -->    <!-- 创建学生 -->  <!--         insert标签:要书写insert这么一个sql语句        id:为这条语句取一个唯一的名字        parameterType:要执行的dao方法中的参数,如果是类的话,必须是全路径名。   -->  <insert id="addStudent" parameterType="com.cxspace.bean.Student">      insert into student values (#{id},#{s_name},#{s_age})  </insert></mapper>
  • 在里面我们配置了一条向数据库插入数据记录的sql语句,并用ognl表达式把java代码中对象的值传入语句。

第三步:写总的配置文件Configuration.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="mysql_development">   <!-- 连接环境信息 -->    <environment id="mysql_development">    <!-- mysql使用什么事物管理方式 -->      <transactionManager type="JDBC">        <property name="" value=""/>      </transactionManager>      <!-- mybatis使用连接池方式来获取连接对象 -->      <dataSource type="POOLED">        <!-- 配置数据库连接信息 -->        <property name="driver" value="com.mysql.jdbc.Driver"/>        <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>        <property name="username" value="root"/>        <property name="password" value="root"/>      </dataSource>    </environment>  </environments><mappers>   <mapper resource="com/cxspace/bean/StudentMapper.xml"/></mappers></configuration>

第四步:写mybatis工具类,维护数据库连接

package com.cxspace.db;import java.io.IOException;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MyBatisUtil {     private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();     private static SqlSessionFactory sqlSessionFactory;     //加载Configuration.xml配置文件     static{         try {             Reader reader = Resources.getResourceAsReader("com/cxspace/config/Configuration.xml");             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);        } catch (IOException e) {             e.printStackTrace();        }     }     /*      * 禁止外部new来调用      */     private MyBatisUtil(){     }     /*      * 获取SqlSession      */     public static SqlSession getSqlSession(){         //从当前线程中获取SqlSession对象         SqlSession sqlSession = threadLocal.get();         //如果SqlSession为空         if (sqlSession == null) {             //在SqlSessionFactory非空的情况下,获取SqlSession对象             sqlSession = sqlSessionFactory.openSession();             //将SqlSession对象与当前线程绑定在一起             threadLocal.set(sqlSession);        }         //返回SqlSession对象         return sqlSession;     }     /*      * 关闭SqlSession与当前线程分开      */     public static void closeSqlSession(){         //从当前线程中获取SqlSession对象         SqlSession sqlSession = threadLocal.get();         //如果SqlSession对象非空         if (sqlSession != null) {             //关闭            sqlSession.close();            //放开当前线程与SqlSession对象的关系,让GC尽快回收            threadLocal.remove();        }     }}

第五步:写StudentDao.java 对数据具体操作

  package com.cxspace.dao;import java.util.List;import javax.jms.Message;import org.apache.ibatis.session.SqlSession;import com.cxspace.bean.Student;import com.cxspace.db.MyBatisUtil;public class StudentDao {    /*     * 增加学生     */    public void add(Student student) throws Exception{        SqlSession sqlSession = null;        try {            sqlSession = MyBatisUtil.getSqlSession();            //事务开始(默认就开始了)            //读取StdentMapper.xml配置的SQL语句            int i = sqlSession.insert("com.cxspace.bean.Student.addStudent",student);            System.out.println("这次操作影响了:"+i+"行");            //事务提交            sqlSession.commit();        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();            //事务回滚            sqlSession.rollback();            throw(e);        }finally{            MyBatisUtil.closeSqlSession();        }    }}

第六步:测试

 package com.cxspace.test;import com.cxspace.bean.Student;import com.cxspace.dao.StudentDao;public class TestCRUD {    public static void main(String[] args) throws Exception {        StudentDao studentDao = new StudentDao();        Student student = new Student();        student.setId(666);        student.setS_name("xyz");        student.setS_age(29);        studentDao.add(student);    }}

最后测试结果

控制台
这里写图片描述

数据库
这里写图片描述

最后,让我们对整个流程做一个总结,看看执行这样一条语句,mybatis做了什么。
这里写图片描述

  • 附上:数据库事务的理论解释
数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行。 事务处理可以确保除非事务性单元内的所有操作都成功完成,否则不会永久更新面向数据的资源。通过将一组相关操作组合为一个要么全部成功要么全部失败的单元,可以简化错误恢复并使应用程序更加可靠。一个逻辑工作单元要成为事务,必须满足所谓的ACID(原子性、一致性、隔离性和持久性)属性。事务是数据库运行中的一个逻辑工作单位,由DBMS中的事务管理子系统负责事务的处理。
0 0
原创粉丝点击