MyBatis入门案例

   1.案例架构

图片 1

2.引入jar 包

图片 2

 

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);
        }
    }

}

 

网站地图xml地图