package com.qiaobc.mybatis.tests;
import java.io.InputStream;
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 com.qiaobc.mybatis.beans.Employee;
import com.qiaobc.mybatis.dao.EmployeeMapper;
public class MybatisTest {
/**
* 增删改测试
* 1. MyBatis允许增删改直接定义以下类型的返回值:Integer、Long、Boolean、void
* 2. sqlSessionFactory.openSession(); //需要手动提交数据
* sqlSessionFactory.openSession(); //主动提交
* @throws Exception
*/
@Test
public void test3() throws Exception {
// 1. 创建SqlSessionFactory实例:根据MyBatis全局配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession实例:其能够执行已经映射的SQL语句;且一个SqlSession对象代表和数据库的一次会话;
// 需要手动提交数据
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee(null, "baobei", "1", "baobei@163.com");
System.out.println(mapper.addEmployee(employee));
System.out.println("id = " + employee.getId());
// Employee employee = new Employee(2, "baobei2", "1", "baobei2@163.com");
// mapper.updateEmployee(employee);
// mapper.deleteEmployee(4);
sqlSession.commit();
} finally {
// 5. 关闭SqlSession实例
sqlSession.close();
}
}
/**
* 面向接口编程
* @throws Exception
*/
@Test
public void test2() throws Exception {
// 1. 创建SqlSessionFactory实例:根据MyBatis全局配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession实例:其能够执行已经映射的SQL语句;且一个SqlSession对象代表和数据库的一次会话;
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 3. 创建接口的实现类对象
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
System.out.println(mapper); //org.apache.ibatis.binding.MapperProxy@4efce9a2
// 将接口与SQL映射文件动态绑定后,MyBatis会为该接口自动地创建一个代理对象,代理对象来执行数据库操作
// 4. 调用接口的查询方法
Employee employee = mapper.getEmployeeById(3);
System.out.println(employee);
} finally {
// 5. 关闭SqlSession实例
sqlSession.close();
}
}
@Test
public void test1() throws Exception {
// 1. 创建SqlSessionFactory实例:根据MyBatis全局配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession实例:其能够执行已经映射的SQL语句;且一个SqlSession对象代表和数据库的一次会话;
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3. 执行已经映射的Sql语句
// SQL语句的唯一标识:statement Unique identifier matching the statement to use.
// 执行SQL语句所需要的参数:A parameter object to pass to the statement.
try {
Employee employee = sqlSession.selectOne("selectEmployee", 2);
System.out.println(employee);
} finally {
// 4. 关闭SqlSession实例
sqlSession.close();
}
}
}