介绍
半自动化的ORM实现
核心对象
1.SqlSessionFactoryBuilder
用过即丢,其生命周期只存在于方法体内
可重用其来创建多个 SqlSessionFactory 实例
负责构建SqlSessionFactory,并提供多个build方法的重载
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
2.SqlSessionFactory
SqlSessionFactory是每个MyBatis应用的核心
作用:创建SqlSession实例
作用域:Application
生命周期与应用的生命周期相同
单例
存在于整个应用运行时,并且同时只存在一个对象实例
SqlSession session = sqlSessionFactory.openSession(boolean autoCommit);
3.SqlSession
包含了执行SQL所需的所有方法
对应一次数据库会话,会话结束必须关闭
线程级别,不能共享,一个request请求期间
SqlSession session = sqlSessionFactory.openSession();
try {
// do work
} finally {
session.close();
}
配置文件
db.porperties
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://127.0.0.1:3306/oa?useUnicode=true&characterEncoding=UTF-8
username=root
password=abc123
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>
<properties resource="db.properties"></properties>
<typeAliases>
<package name="cn.zb.oa.pojo"></package>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driverClass}"/>
<property name="url" value="${jdbcUrl}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.zb.oa.dao"></package>
</mappers>
</configuration>
mapper.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="cn.zb.oa.dao.EnterpriseMapper">
<insert id="createEnterprise" parameterType="Enterprise">
INSERT INTO enterprise(id,name,abbr,info) VALUES (#{id},#{name},#{abbr},#{info})
</insert>
<select id="getEnterpriseList" resultType="cn.zb.oa.pojo.Enterprise">
select * from enterprise
</select>
</mapper>