Mybatis_05/26

主要类的介绍

1)Resources: mybatis中的一个类, 负责读取主配置文件
    InputStream in = Resources.getResourceAsStream("mybatis.xml");

2)SqlSessionFactoryBuilder : 创建SqlSessionFactory对象, 
     SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();
     //创建SqlSessionFactory对象
     SqlSessionFactory factory = builder.build(in);
 3)SqlSessionFactory : 重量级对象, 程序创建一个对象耗时比较长,使用资源比较多。
    在整个项目中,有一个就够用了。
    SqlSessionFactory:接口,接口实现类: DefaultSqlSessionFactory
    SqlSessionFactory作用: 获取SqlSession对象。SqlSession sqlSession = factory.openSession();

 4) openSession()方法说明:
   1. openSession() :无参数的, 获取是非自动提交事务的SqlSession对象
   2. openSession(boolean): openSession(true)  获取自动提交事务的SqlSession. 
	                        openSession(false)  非自动提交事务的SqlSession对象
   3. SqlSession: 
        SqlSession接口 :定义了操作数据的方法 例如 selectOne() ,selectList()      ,insert(),update(), delete(), commit(), rollback()
        SqlSession接口的实现类DefaultSqlSession。

使用要求: SqlSession对象不是线程安全的,需要在方法内部使用, 在执行sql语句之前,使用openSession()获取SqlSession对象。
在执行完sql语句后,需要关闭它,执行SqlSession.close(). 这样能保证他的使用是线程安全的。

实现工具类

MybatisUtils:

package com.sdut.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.InputStream;

public class MybatisUtils {

    private static SqlSessionFactory factory = null;
    //静态块:读文件
    static {
        String config = "mybatis.xml";
        try {
            InputStream in = Resources.getResourceAsStream(config);
            //创建SqlSessionFactory对象
            factory = new SqlSessionFactoryBuilder().build(in);
            //
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession方法
    public static SqlSession getSqlSession() {
        SqlSession sqlSession = null;
        if(factory != null) {
            sqlSession = factory.openSession();   //非自动提交事务
        }
        return sqlSession;
    }
}

利用Dao层操作数据库

StudentDao:

package com.sdut.dao;

import com.sdut.entity.Student;

import java.util.List;

public interface StudentDao {
    //查询所有
    List<Student> selectAllStudents();
    //插入
    int insertStudent(Student student);
    //删除
    int deleteStudentById(int id);
}

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="com.sdut.dao.StudentDao">
    <select id="selectAllStudents" resultType="com.sdut.entity.Student">
        select * from student order by id
    </select>
    <insert id="insertStudent">
        insert into student values(#{id}, #{name}, #{email}, #{age})
    </insert>
    <delete id="deleteStudentById">
        delete from student where id=#{id}
    </delete>
</mapper>

StudentDao接口实现类:

package com.sdut.dao.impl;

import com.sdut.dao.StudentDao;
import com.sdut.entity.Student;
import com.sdut.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentDaoImpl implements StudentDao {     //ctrl+o
    @Override
    public List<Student> selectAllStudents() {
        //获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        String sqlId = "com.sdut.dao.StudentDao.selectAllStudents";
        List<Student> studentList = sqlSession.selectList(sqlId);
        sqlSession.close();
        return studentList;
    }

    @Override
    public int deleteStudentById(int id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        String sqlId = "com.sdut.dao.StudentDao.deleteStudentById";
        int result = sqlSession.delete(sqlId, id);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int insertStudent(Student student) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        String sqlId = "com.sdut.dao.StudentDao.insertStudent";
        int result = sqlSession.insert(sqlId, student);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }
}

Test测试类:

package com.sdut;

import com.sdut.dao.StudentDao;
import com.sdut.dao.impl.StudentDaoImpl;
import com.sdut.entity.Student;
import org.junit.Test;

import java.util.List;

public class MybatisTest {
    @Test
    public void testselectAllStudents() {
        StudentDao studentDao = new StudentDaoImpl();
        List<Student> studentList = studentDao.selectAllStudents();
        for(Student stu : studentList) {
            System.out.println(stu);
        }
    }

    @Test
    public void testinsertStudent() {
        StudentDao studentDao = new StudentDaoImpl();

        Student student = new Student();
        student.setId(1004);
        student.setName("孙悟空");
        student.setEmail("huaguoshan.com");
        student.setAge(10000);

        int result = studentDao.insertStudent(student);
        System.out.println("结果为:" + result);
    }

    @Test
    public void testdeleteStudentById() {
        StudentDao studentDao = new StudentDaoImpl();
        int result = studentDao.deleteStudentById(1001);
        System.out.println("结果为:" + result);
    }
}

运行结果:

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值