1.MyBatis接口式编程简介
(1)接口式编程
原生: Dao ====> DaoImpl
mybatis: Mapper ====> xxMapper.xml
(2)SqlSession代表和数据库的一次会话;用完必须关闭;
(3)SqlSession和connection一样它都是非线程安全。每次使用都应该去获取新的对象。
(4)mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象。(将接口和xml进行绑定)
EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);
(5)两个重要的配置文件:
① mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行环境信息
② sql映射文件:保存了每一个sql语句的映射信息:将sql抽取出来。
2.接口式编程的流程
(1) 创建SqlSessionFactory
(2) 创建SqlSession
(3) 获取EmployeeMapper
(4) 传入参数
(5) 关闭资源
eg:
public void test() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = employeeMapper.getEmployeeID(1);
System.out.println(employee);
sqlSession.close();
}
3.相关配置文件及函数
3.1 getSqlSessionFactory()函数
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
3.2 EmployeeMapper接口
public interface EmployeeMapper {
public Employee getEmployeeID(Integer id);
}
3.3 EmployeeMapper.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="dao.EmployeeMapper">
<!--
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
public Employee getEmpById(Integer id);
-->
<select id="getEmployeeID" resultType="bean.Employee">
select * from employee where id = #{id}
</select>
</mapper>
3.4 全局配置文件(mybatis-config.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/MyBatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="LF@0827" />
</dataSource>
</environment>
</environments>
<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
<mappers>
<mapper resource="EmployeeMapper.xml" />
</mappers>
</configuration>
3.5 文件目录
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191011221730971.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNTk2NTY4,size_16,color_FFFFFF,t_70)