MyBatis的学习(二):MyBatis的操作示例
目录
传统操作
插入数据示例
- 编写Dao中的插入学生方法
/**
* 插入学生
* @param student 参数是需要插入到数据库的学生
* @return 返回值是插入操作影响的行数
*/
public int insertStudent(Student student);
- 在mapper文件中创建映射
<insert id="insertStudent">
insert into student(id,name,email,age) values(#{id},#{name},#{email},#{age})
</insert>
- 编写一个测试类
package com.liang;
import com.liang.entity.Student;
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.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @author liang
* @date 编写日期: 2022/3/17 19:45
*/
public class TestMybatis {
//测试插入功能
@Test
public void testInsert() throws IOException {
//访问mybatis读取student数据
//1. 定义mybatis主配置
String config = "mybatis.xml";
//2. 读取这个文件
InputStream in = Resources.getResourceAsStream(config);
//3. 创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//4. 创建SqlSessionFactory对象
SqlSessionFactory factory = builder.build(in);
//5. 获取SqlSession对象【重要】
SqlSession sqlSession = factory.openSession();
//6. 指定执行sql语句的标识,sql映射文件中的namespace+"."+标签的id值【重要】
String sqlId = "com.liang.dao.StudentDao.insertStudent";
//7. 执行sql语句
Student student = new Student(1003,"王五","wangwu@qq.com",25);
int num = sqlSession.insert(sqlId,student);
if(num==1){
//mybati是默认没有自动提交事务的,需要手动提交
sqlSession.commit();
}
//8. 输出结果
//students.forEach(student -> System.out.println(student));
System.out.println("执行的结果是:"+num);
//9. 关闭资源
sqlSession.close();
}
}
- 如果想要开启日志功能,在主配置文件的configuration下加入
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
主要类的介绍
-
Resourced:mybatis中的一个类,负责读取配置文件
InputStream in = Resources.getResourceAsStream(config);
-
SqlSessionFactoryBuilder:创建SqlSessionFactory对象
//3. 创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //4. 创建SqlSessionFactory对象 SqlSessionFactory factory = builder.build(in);
-
SqlSessionFactory:重量级对象,程序创建一个对象耗时比较长,使用的资源比较多。
在整个项目中,有一个就足够了。
SqlSessionFactory:接口,接口实现类:DefaultSqlSessionFactory
SqlSessionFactory作用:获取SqlSession对象。
SqlSession sqlSession = factory.openSession();
openSession()方法说明:
-
openSession():无参数的,获取的是非自动提交事务的SqlSeesion对象
-
openSession(boolen): openSession(true) 获取自动提交事务的SqlSession.
openSession(false) 非自动提交事务的SqlSession对象
-
-
SqlSession:
SqlSession接口:定义了操作数据的方法,例如:selectOne(),selectList(),insert(),update(),delete(),commit()…
使用要求:SqlSession对象不是线程安全的,需要再方法内部使用,在执行sql语句之前,使用openSession()获取SqlSession对象,在执行完sql语句之后,需要关闭它,执行SqlSession.close(),这样才能保证它的使用是线程安全的。
创建Mybatis工具类
- 创建一个util包,里面编写MybatisUtils工具类
package com.liang.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;
/**
* Mybatis的工具类
* @author liang
* @date 编写日期: 2022/3/17 20:53
*/
public class MybatisUtils {
public static SqlSessionFactory factory = null;
static {
try {
//配置文件,项目中的是什么就写什么
String config = "mybatis.xml";
InputStream in = Resources.getResourceAsStream(config);
//创建SqlSessionFactory对象,使用SqlSessionFactoryBuild
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
factory = builder.build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取SqlSession的方法
* @return 返回SqlSession对象
*/
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
if(factory != null){
//非自动提交事务
sqlSession = factory.openSession();
}
return sqlSession;
}
}
- 用工具类简化
package com.liang;
import com.liang.entity.Student;
import com.liang.utils.MybatisUtils;
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;
import java.util.List;
/**
* @author liang
* @date 编写日期: 2022/3/17 2:13
*/
public class MyApp2 {
public static void main(String[] args) throws IOException {
SqlSession sqlSession = MybatisUtils.getSqlSession();
//指定执行sql语句的标识,sql映射文件中的namespace+"."+标签的id值【重要】
String sqlId = "com.liang.dao.StudentDao"+"."+"selectStudents";
//执行sql语句
List<Student> students = sqlSession.selectList(sqlId);
for(Student student:students){
System.out.println("查询的学生:"+student);
}
//关闭资源
sqlSession.close();
}
}
添加xml文件模板
- 点击file然后点击设置
- 按图中步骤进行添加,注意第二步要选择files
- 添加之后可以直接新建
传统Dao的执行
- 在dao包下写接口的实现类
package com.liang.dao.impl;
import com.liang.dao.StudentDao;
import com.liang.entity.Student;
import com.liang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
/**
* @author liang
* @date 编写日期: 2022/3/17 23:14
*/
public class StudentDaoImpl implements StudentDao {
/**
* 查找所有学生的信息
*/
@Override
public List<Student> selectStudents() {
String sqlId = "com.liang.dao.StudentDao.selectStudents";
//获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行sql语句
List<Student> students = sqlSession.selectList(sqlId);
sqlSession.close();
//关闭资源
return students;
}
}
- 测试
package com.liang;
import com.liang.dao.StudentDao;
import com.liang.dao.impl.StudentDaoImpl;
import com.liang.entity.Student;
import org.junit.Test;
import java.util.List;
/**
* @author liang
* @date 编写日期: 2022/3/17 23:23
*/
public class TestMybatis {
@Test
public void testSelectStudent(){
StudentDao dao = new StudentDaoImpl();
List<Student> students = dao.selectStudents();
for(Student stu:students){
System.out.println(stu);
}
}
}
Mybatis的动态代理
动态代理的条件分析
List<Student> students = dao.selectStudents();
1. dao对象,类型是StudentDao,全限定名称是:com.liang.dao.StudentDao
全限定名称和namespace一样
2. 方法名称,selectStudents。这个方法就是mapper文件中的id值selectStudent
3. 通过Dao中的方法的返回值,也可以确定Mybatis要调用的方法
如果返回的是List,调用的就是SqlSession.selectList()
如果返回是int,或者非List,看mapper文件中的标签是inset还是update就会调用SqlSeesion的对应方法
mybatis的动态代理:mybatis会根据dao方法的调用,获取执行sql语句的信息
mybatis根据dao接口,创建出一个dao接口的实现类,并创建这个类的对象
完成session方法的调用,访问数据库
动态代理举例
测试插入数据
@Test
public void testInsertStudent(){
/**
* 使用mybatis的动态代理机制,使用SqlSession.getMapper(dao接口)
* getMapper可以获取dao接口对应的实现类对象
*/
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
//调用dao方法,执行数据库操作
int i = dao.insertStudent(new Student(1005,"小梁","123@qq.com",28));
if(i==1){
sqlSession.commit();
System.out.println("执行插入成功!");
sqlSession.close();
}
}
插入成功!