美文网首页
MyBatis学习笔记 - MyBatis CRUD基本使用

MyBatis学习笔记 - MyBatis CRUD基本使用

作者: 崔寒冰 | 来源:发表于2018-08-14 23:48 被阅读0次

使用MyBatis必要配置如下:

(1) MyBatis配置信息,mybatis.xml

  • mybatis.xml中配置数据库必须的基本信息:驱动,url,用户名,密码等必须信息,最大连接数,超时等非必须信息。
  • 配置实体类映射配置文件(mapper标签下配置实体类配置文件路径)
  • IDEA文件目录中的位置src/resource/mybatis.xml

(2) 实体类映射及数据库表操作方法配置 xxxMapper.xml

MyBatis使用案例

用例简介:对学生信息进行管理,数据库字段包括 s_id,s_name,s_height

1.项目中导入MyBatis依赖(maven或直接下载jar导入)

2.添加mybatis配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
    <!--默认连接环境信息-->
    <environments default="mysql_developer">
        <!--连接环境信息  取任意一个-->
        <environment id="mysql_developer">
            <!--表示mybatis使用什么方式管理(jdbc)-->
            <transactionManager type="JDBC"></transactionManager>
            <!--表示mybatis使连接池获取连接-->
            <dataSource type="POOLED">
                <!--配置数据库必要的4个属性-->
                                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
        <environment id="oracle_developer">
            <!--表示mybatis使用什么方式管理(jdbc)-->
            <transactionManager type="JDBC"></transactionManager>
            <!--表示mybatis使连接池获取连接-->
            <dataSource type="POOLED">
                <!--配置数据库必要的4个属性-->
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mybatis/StudentMapper.xml"/>
    </mappers>
</configuration>

3.封装MyBatis工具类

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

public class MyBatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;
    private MyBatisUtil() {
    }
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession
     */
    public static SqlSession getSqlSesson() {
//从当前线程获取sqlSession对象
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null && sqlSessionFactory != null) {
            sqlSession = sqlSessionFactory.openSession();
//将sqlsession与当前线程绑定起来
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 关闭 SqlSession
     */
    public static void closeSqlSesson() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
//关闭sqlSession
            sqlSession.close();
//分开当前线程与 SqlSession,目的让GC尽早回收
            threadLocal.remove();
        }
    }
}

4.编写Student实体类,StudentDao,StudentDaoImpl

Student实体类

package com.test.mybatis;
public class Student {
    private Integer id;
    private String name;
    private Float height;
    public Student(Integer id, String name, Float height) {
        this.id = id;
        this.name = name;
        this.height = height;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Float getHeight() {
        return height;
    }
    public void setHeight(Float height) {
        this.height = height;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", height=" + height +
                '}';
    }
}

StudentDao接口

package com.test.mybatis;

import java.util.List;

interface StudentDao {
   void add(Student student);

   boolean deleteById(int id);

   boolean deleteAll();

   Student findById(int id);

   List<Student> findAll();

   void update(Student student);
}

StudentDaoImpl接口实现类

package com.test.mybatis;

import org.apache.ibatis.session.SqlSession;
import utils.MyBatisUtil ;

import java.util.List;

/**
 * @author 45000460
 */
public class StudentDaoImpl implements StudentDao{
    /**
     * 增加
     */
    @Override
    public void add(Student student) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil .getSqlSesson();
            sqlSession.insert(Student.class.getName() + ".addBean", student);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            System.out.println(e.getMessage());
            throw e;
        } finally {
            MyBatisUtil .closeSqlSesson();
        }
    }

    /**
     * 根据ID删除
     */
    @Override
    public boolean deleteById(int id) {
        SqlSession sqlSession = null;
        boolean isSuccess = false;
        try {
            sqlSession = MyBatisUtil .getSqlSesson();
            int count = sqlSession.delete(Student.class.getName() + ".deleteById", id);
            sqlSession.commit();
            isSuccess = count != 0;
            return isSuccess;
        } catch (Exception e) {
            sqlSession.rollback();
            System.out.println(e.getMessage());
            throw e;
        } finally {
            MyBatisUtil .closeSqlSesson();
        }
    }

    /**
     * 删除所有
     */
    @Override
    public boolean deleteAll() {
        SqlSession sqlSession = null;
        boolean isSuccess = false;
        try {
            sqlSession = MyBatisUtil .getSqlSesson();
            int count = sqlSession.delete(Student.class.getName() + ".deleteAll");
            sqlSession.commit();
            isSuccess = count != 0;
            return isSuccess;
        } catch (Exception e) {
            sqlSession.rollback();
            System.out.println(e.getMessage());
            throw e;
        } finally {
            MyBatisUtil .closeSqlSesson();
        }
    }

    /**
     * 通过id查询
     */
    @Override
    public Student findById(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil .getSqlSesson();
            Student student = sqlSession.selectOne(Student.class.getName() + ".findBeanById", id);
            sqlSession.commit();
            return student;
        } catch (Exception e) {
            sqlSession.rollback();
            System.out.println(e.getMessage());
            throw e;
        } finally {
            MyBatisUtil .closeSqlSesson();
        }
    }

    /**
     * 查询所有
     */
    @Override
    public List<Student> findAll() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil .getSqlSesson();
            List<Student> studentList = sqlSession.selectList(Student.class.getName() + ".findAll");
            sqlSession.commit();
            return studentList;
        } catch (Exception e) {
            sqlSession.rollback();
            System.out.println(e.getMessage());
            throw e;
        } finally {
            MyBatisUtil .closeSqlSesson();
        }
    }

    /**
     * 更新(修改)
     */
    @Override
    public void update(Student student) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil .getSqlSesson();
            sqlSession.update(Student.class.getName() + ".update", student);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            System.out.println(e.getMessage());
            throw e;
        } finally {
            MyBatisUtil .closeSqlSesson();
        }
    }

//测试
    public static void main(String[] strings) {
        StudentDaoImpl studentDaoImpl = new StudentDaoImpl();
        studentDaoImpl.add(new Student(null, "小明", 180.0f));
//根据ID查询
//        Student student = studentDaoImpl.findById(16);
//        System.out.println(student.toString());

////查询所有学生
//        List<Student> list = studentDaoImpl.findAll();
//        for (Student student : list) {
//            System.out.println(student.toString());
//        }
//修改学生信息
//        Student student = studentDaoImpl.findById(15);
//        System.out.println("原数据:\n" + student.toString());
//        student.setName("修改后名字2");
//        studentDaoImpl.update(student);
//        Student student2 = studentDaoImpl.findById(15);
//        System.out.println("修改后数据:\n" + student2.toString());

//        根据ID删除学生数据
//        studentDaoImpl.deleteById(14);

//        删除所有数据
//        studentDaoImpl.deleteAll();


    }
}

5.配置Student实体类与数据库的对应关系(否则程序无法找到实体类属性与数据库字段之间的对应关系),需要依赖配置文件StudentMapper.xml(在mybatis配置文件中mapper标签中配置)

配置 StudentMapper.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- 映射文件,解决数据库表和实体类的关系 -->
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >


<!-- namespace属性 名称空间,必须唯一  -->
<mapper namespace="com.test.mybatis.Student">
    <!-- resultMap   映射实体与表-->
    <!-- id          表示实体与表的映射去一个唯一名字-->
    <!-- type        表示实体全路径名-->

    <!--当实体属性与表字段不相同的时候必须配置一下代码 ,且查询返回值类型使用resultMap=resultMap的ID-->
    <!--当实体属性与表字段相同的时候可选 查询返回值使用 resultType -->
    <resultMap id="studentMap" type="com.test.mybatis.Student">
        <!-- id 标签:映射主键属性-->
        <!-- result 标签:映射非主键属性-->
        <!-- property 属性: 实体的属性名 -->
        <!--column 属性 表的字段名  -->
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="height" column="height"/>

    </resultMap>
    
    <!-- insert 属性 :要书写insert sql语句-->
    <!-- id 属性: 表示insert为sql语句取唯一的名字 -->
    <!-- parameterType 属性 要执行dao 中方法的参数 ,如果是类的话,必须使用全路径类-->
    <insert id="add">
        insert into students(id,name,height)values (1,"小明",180)
    </insert>

    <insert id="addBean" parameterType="com.test.mybatis.Student">
        insert into students(id,name,height)values (#{id},#{name},#{height})
    </insert>
    <!--根据ID删除-->
    <delete id="deleteById" parameterType="int">
        delete from students where id=#{id}
    </delete>

    <!--删除所有-->
    <delete id="deleteAll" >
        delete from students
    </delete>

    <!--根据id查询学生-->
    <select id="findBeanById" parameterType="int" resultType="com.test.mybatis.Student">
        select * from students where id=#{id}
    </select>

    <!--查询所有学生,结果保存在集合中 配置时只需要写出返回值集合中的数据类型即可 即Student的全路径名即可-->
    <select id="findAll" resultType="com.test.mybatis.Student">
    select * from students
</select>
    
    <!--更新-->
    <update id="update" parameterType="com.test.mybatis.Student">
       update students set name=#{name},height = #{height} where id=#{id}
    </update>
    
</mapper>

指定StudentMapper.xml配置文件路径

...
    <mappers>
        <mapper resource="com.test.mybatis/StudentMapper.xml"/>
    </mappers>

测试用例结构目录:


测试用例结构目录.png

相关文章

网友评论

      本文标题:MyBatis学习笔记 - MyBatis CRUD基本使用

      本文链接:https://www.haomeiwen.com/subject/dqrvbftx.html