package com.ltlrl.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.InputStream;
public class MyBatisUtils {
//定义 SqlSessionFactory
private static SqlSessionFactory factory = null;
static {
//使用 静态块 创建一次 SqlSessionFactory
try{
String config = "mybatis.xml";
//读取配置文件
InputStream in = Resources.getResourceAsStream(config);
//创建 SqlSessionFactory 对象
factory = new SqlSessionFactoryBuilder().build(in);
}catch (Exception e){
factory = null;
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
SqlSession session = null;
if( factory != null){
session = factory.openSession();
}
return session;
}
}
使用 MyBatisUtil 类
@Test
public void testUtils() throws IOException {
SqlSession session = MyBatisUtil.getSqlSession();
List studentList = session.selectList("com.ltlrl.dao.StudentDao.selectStudents");
studentList.forEach( student -> System.out.println(student));
session.close();
}
事务自动提交
在mybatis中事务默认不是自动提交的,需要我们来手动进行提交
sqlSession.commit();//提交事务
将openSession方法的参数设为true就能实现自动提交
session = factory.openSession(true);Dao 代理
因为真正对数据库进行操作的工作其实是由框架通过mapper中的SQL完成的,所以MyBatis框架就抛开了 Dao 的实现类,直接定位到映射文件mapper中的相应SQL语句,对DB进行操作。这种对Dao的实现方式称为Mapper的动态代理方式。Mapper动态代理方式无需我们实现Dao接口。接口是由MyBatis结合映射文件自动生成的动态代理实现的。
getMapper 获取代理对象只需调用 SqlSession的getMapper()方法,即可获取指定接口的实现类对象。
该方法的参数为指定Dao接口类的class值。
qlSession sqlSession = MyBatisUtils.getSqlSession(); StudentDao dao =sqlSession.getMapper(StudentDao.class);使用 Dao 代理对象方法执行 sql 语句
public void SelectStudents(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao =sqlSession.getMapper(StudentDao.class);
//调用dao的方法,执行数据库的操作
Liststudents =dao.selectStudents();
for(Student stu:students){
System.out.println("学生="+stu);
}
}
public void InsertStudent(){
SqlSession sqlSession =MyBatisUtils.getSqlSession();
StudentDao dao =sqlSession.getMapper(StudentDao.class);
Student student =new Student();
student.setId(1007);
student.setName("李飞");
student.setEmail("lifei@qq.com");
student.setAge(27);
int nums =dao.insertStudent(student);
sqlSession.commit();
System.out.println("添加对象的数量:"+nums);
}
public void testUpdate(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao =sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setId(1006);
student.setAge(28);
int nums = dao.updateStudent(student);
sqlSession.commit();
System.out.println("修改数据的数量:"+nums);
}
public void testDelete(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao =sqlSession.getMapper(StudentDao.class);
int nums = dao.deleteStudent(1006);
sqlSession.commit();
System.out.println("删除数据的数量:"+nums);
}



