1.案例架构

2.引入jar 包

3.书写配置文件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>
    <!-- 设置别名 -->
    <typeAliases>
        <!-- 通过package, 可以直接指定package的名字, mybatis会自动扫描你指定包下面的javabean, 并且默认设置一个别名,默认的名字为:
            javabean 的首字母小写的非限定类名来作为它的别名 -->
            <!-- type指的是javabean的完全限定名 alias就是指代别名 -->
<!-- <typeAlias alias="student" type="cn.entity.Student" /> -->
        <package name="cn.entity" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc的事务 -->
            <transactionManager type="JDBC" />
            <!-- 使用自带的连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
                <property name="username" value="test" />
                <property name="password" value="test" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="cn/dao/StudentDAO.xml" />
    </mappers>
</configuration>

4.创建实体类 Student

package cn.entity;
/**
 * 学生实体类
 * @author hyj
 *
 */
public class Student {
     private Integer id;//编号
     private Integer age;//年龄
     private String name;//姓名
    public Student() {
    }
    public Student(Integer id, Integer age, String name) {
        super();
        this.id = id;
        this.age = age;
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", age=" + age + ", name=" + name + "]";
    }

}

5.创建学生的Dao以及Dao的实现

package cn.dao;

import java.io.IOException;
import java.util.List;

import cn.entity.Student;

/**
 * 学生的dao
 * @author hyj
 *
 */
public interface StudentDao {
    /**
     * 保存学生
     * @param stu 学生对象
     * @return 受影响行数
     * @throws IOException
     */
     int save(Student stu) throws IOException;

     /**
      * 根据id删除学生信息
      * @param id
      * @return
      */
     int delete(Integer id);

     /**
      * 查看学生列表
      * @return
      */
      List<Student> studentList();

      /**
       * 根据学生姓名模糊查询学生信息
       * @param name
       * @return
       */
      List<Student> byNameList(String name);

      /**
       * 根据学生对象模糊查询学习姓名
       * @param stu
       * @return
       */
      List<Student> byNameList(Student stu);

      /**
       * 更新学生信息
       * @param stu
       * @return
       */
      int updateStudent(Student stu);

}
package cn.dao.impl;

import java.io.IOException;
import java.io.Reader;
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.Before;

import cn.dao.StudentDao;
import cn.entity.Student;
import cn.util.SqlSessionUtil;

/**
 * 学生的dao实现类
 *
 * @author hyj
 *
 */
public class StudenDaoImpl implements StudentDao {

    SqlSession session = SqlSessionUtil.getSqlSession();

    /**
     * 添加学生信息
     */
    @Override
    public int save(Student stu) throws IOException {
        int result = session.insert("insertStudent", stu);
        // 提交事务
        session.commit();
        SqlSessionUtil.closeSqlSession();
        return result;

    }

    /**
     * 根据id删除学生信息
     */
    @Override
    public int delete(Integer id) {
        int result = session.delete("deletStudent", id);
        session.commit();
        SqlSessionUtil.closeSqlSession();
        return result;
    }

    /**
     * 查询学生列表
     *
     * @return
     */
    @Override
    public List<Student> studentList() {
        List<Student> students = session.selectList("studentlist");
        SqlSessionUtil.closeSqlSession();
        return students;
    }

    /**
     * 根据学生姓名模糊查询学生列表:传入的参数是普通字符串
     */
    @Override
    public List<Student> byNameList(String name) {
        List<Student> students = session.selectList("byName", name);
        SqlSessionUtil.closeSqlSession();
        return students;
    }

    /**
     * 根据学生对象模糊查询学生列表:传入的参数对象
     */
    @Override
    public List<Student> byNameList(Student stu) {
        List<Student> students = session.selectList("byStu", stu);
        SqlSessionUtil.closeSqlSession();
        return students;
    }

    /**
     * 更新学生信息
     */
    @Override
    public int updateStudent(Student stu) {
        int result = session.update("updatestu", stu);
        session.commit();
        SqlSessionUtil.closeSqlSession();
        return result;
    }

}

6.书写StudentDao的配置文件StudentDAO.xml

<?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="cn.dao">
    <!-- 添加一条学生记录 -->
    <insert id="insertStudent" parameterType="student">
        insert into
        student(id,age,name) values(id.nextval,#{age},#{name})
        <!-- 自增列的值 -->
        <selectKey
            keyProperty="id" resultType="int">
            SELECT ID.Nextval as ID from DUAL
        </selectKey>
    </insert>

    <!-- 根据id删除学生记录 -->
    <delete id="deletStudent">
        delete from student where id=#{value}
    </delete>

    <!-- 查询所有学生记录 -->
    <select id="studentlist" resultType="student">
        select * from student
    </select>
    <!-- 更新学生信息 -->
    <update id="updatestu" parameterType="student">
        update student set age=#{age},name=#{name} where id=#{id}
    </update>
    <!-- 模糊查询 当入参是普通字符串时 -->
    <select id="byName" resultType="student">
     select * from student where name like concat('%',#{name},'%')
        <!-- 方式一 -->
        <!-- select * from student where name like '%${value}%' -->
        <!-- select * from student where name like concat('%',#{name},'%') -->
    </select>
    <!-- 模糊查询 当入参是对象时 -->
    <select id="byStu" resultType="student">
        <!-- 方式一 -->
        <!-- select * from student where name like '%${name}%' -->
        <!-- 方式二 -->
        select * from student where name like concat('%',#{name},'%')
    </select>
</mapper>

7.工具类:用于获取SqlSession对象  SqlSessionUtil

package cn.util;

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;

/**
 * 这个工具类主要用来创建sqlsession对象
 * @author hyj
 *
 */
public  class SqlSessionUtil {
    //定义reader对象
      static Reader reader;
      static SqlSessionFactory sqlSessionFactory;
      static SqlSession sqlsession;
      //静态代码初始化给reader,sessionFactory初始化
    static{
        try {
            reader=Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取SqlSession对象
     * @return SqlSession对象
     */
   public static SqlSession getSqlSession(){
        sqlsession=sqlSessionFactory.openSession();
        return sqlsession;
   }

   /**
    * 关闭sqlsession
    */
   public static void closeSqlSession(){
       if(sqlsession!=null){
           sqlsession.close();
       }
   }
}

8.测试类:

package cn.test;

import java.io.IOException;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import cn.dao.StudentDao;
import cn.dao.impl.StudenDaoImpl;
import cn.entity.Student;

public class StudentTest {
    StudentDao sd;

    @Before
    public void before() {
        // 创建Studentdao对象
        sd = new StudenDaoImpl();
    }

    /**
     * 添加学生信息
     *
     * @throws IOException
     */
    @Test
    public void addTest() throws IOException {
        // 创建学生对象
        Student stu = new Student();
        stu.setAge(20);
        stu.setName("笑话");
        System.out.println("保存前:\n"+stu);
        // 调用dao保存
        int save = sd.save(stu);
        System.out.println("保存后:\n"+stu);
        System.out.println("保存成功");
    }

    /**
     * 删除学生信息
     *
     * @throws IOException
     */
    @Test
    public void deleteTest() throws IOException {
        // 调用dao保存
        int save = sd.delete(2);
        System.out.println("删除成功");
    }

    /**
     * 查看学生列表
     */
    @Test
    public void studentList() {
        List<Student> studentList = sd.studentList();
        for (Student student : studentList) {
            System.out.println(student);
        }
    }

    /**
     * 更新学生信息
     */
    @Test
    public void updateStudent() {
        Student stu = new Student();
        stu.setAge(99);
        stu.setName("呵呵");
        stu.setId(5);
        int result = sd.updateStudent(stu);
        System.out.println("更新成功"+result);
    }

    /**
     * 根据学生姓名模糊查询学生列表:当传递的参数是普通类型时
     */
    @Test
    public void byNameList() {
        List<Student> studentList = sd.byNameList("1");
        for (Student student : studentList) {
            System.out.println(student);
        }
    }

    /**
     * 根据学生对象模糊查询学生列表:当传递的参数是对象时
     */
    @Test
    public void byStuList() {
        // 创建学生对象
        Student stu = new Student();
        stu.setName("1");
        List<Student> studentList = sd.byNameList(stu);
        for (Student student : studentList) {
            System.out.println(student);
        }
    }

}

MyBatis入门案例的更多相关文章

  1. MyBatis入门案例、增删改查

    一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...

  2. MyBatis入门案例 增删改查

    一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...

  3. Mybatis入门案例中设计模式的简单分析

    Talk is cheap, show me the code! public class TestMybatis { public static void main(String[] args) t ...

  4. mybatis入门案例自定义实现

    mybatis入门案例自定义实现 一.需要实现的类和接口 public static void main(String[] args) throws Exception{ //1.读取配置文件 Inp ...

  5. mybatis入门案例分析

    mybatis入门案例分析 一.设计模式分析 public class MybatisTest { public static void main(String[] args) throws Exce ...

  6. 03 Mybatis:01.Mybatis课程介绍及环境搭建&&02.Mybatis入门案例

    mybatis框架共四天第一天:mybatis入门 mybatis的概述 mybatis的环境搭建 mybatis入门案例 -------------------------------------- ...

  7. intellij IDEA Mybatis入门案例

    最近打算学习ssm框架  Mybatis 作为入门的第一个持久层框架,学习起来实在费劲.故写此文章作为入门案例. 先打开 IDEA建立一个Maven项目,目录结构如下: 源代码已经上传至GitHub ...

  8. 一、mybatis入门案例

    今天学习了mybatis框架,简单记录一下mybatis第一个入门案例,目标是使用Mybatis作为持久层框架,执行查询数据的SQL语句并且获取结果集 基本步骤: 物理建模 逻辑建模 引入依赖 创建持 ...

  9. 阶段3 1.Mybatis_02.Mybatis入门案例_1.mybatis的入门

    H:\BaiDu\黑马传智JavaEE57期 2019最新基础+就业+在职加薪\讲义+笔记+资料\主流框架\31.会员版(2.0)-就业课(2.0)-Mybatis\mybatis\mybatis_d ...

随机推荐

  1. Morris post order traversal algorithm

    Sept. 5, 2015 花时间把代码读明白, 比光看书强. 动手写代码, 改代码,  兴趣是最好的老师. 多记几个例子, 增加情趣. 举个例子关于中序遍历,            4       ...

  2. Caffe Python MemoryDataLayer Segmentation Fault

    转载请注明出处,楼燚(yì)航的blog,http://home.cnblogs.com/louyihang-loves-baiyan/ 因为利用Pyhon来做数据的预处理比较方便,因此在data_l ...

  3. python中的迭代、生成器等等

    本人对编程语言实在是一窍不通啊...今天看了廖雪峰老师的关于迭代,迭代器,生成器,递归等等,word天,这都什么跟什么啊... 1.关于迭代 如果给定一个list或tuple,我们可以通过for循环来 ...

  4. [bzoj3932][CQOI2015][任务查询系统] (主席树)

    Description 最近实验室正在为其管理的超级计算机编制一套任务管理系统,而你被安排完成其中的查询部分.超级计算机中的 任务用三元组(Si,Ei,Pi)描述,(Si,Ei,Pi)表示任务从第Si ...

  5. python3条件控制if

    Python条件语句是通过一条或多条语句的执行结果(为真或假)来决定执行哪部分代码. if语句 if语句的一般形式如下: if 条件1: 语句1 elif 条件2: 语句2 else: 语句3 其意思 ...

  6. CMakeList.txt/Clion中添加头文件和库

    cmake_minimum_required(VERSION 3.6) project(capi_lua) include_directories(/usr/include) find_library ...

  7. [LeetCode] Hamming Distance 汉明距离

    The Hamming distance between two integers is the number of positions at which the corresponding bits ...

  8. [LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  9. H5是什么,CSS3又是什么?

    经常有客户咨询说你们会做H5吗,就像这个,拿过来一看,一个上下滑动的贺卡,这已经成为了大部分人对H5的理解,甚至很多大公司都推出了制作这种动画的工具,可以快速生成此类页面.(其实,这就用到了一些CSS ...

  10. 【转载】<mvc:annotation-driven />注解意义

    本文转载自:http://kingliu.iteye.com/blog/1972973 <mvc:annotation-driven /> 是一种简写形式,完全可以手动配置替代这种简写形式 ...