一、特点:采用配置文件动态管理SQL语句,并含有输入映射、输出映射机制 以及数据库连接池配置的持久层框架。
二、构成:
1. 数据源配置文件
2. SQL映射配置文件
3. 会话工厂与会话
4. 执行器和底层封装对象
数据源配置文件 SqlMapConfig.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>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3307/mybatis_test?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlmap/UserMapper.xml"/>
</mappers>
</configuration>
SQL映射配置文件 Mapper.xml 配置任何类型的SQL语句
将数据库中取出的字段一一对应到java对象和或Map对象中。
–Mapper文件,完成了对SQL语句以及输入输出参数的映射配置。
<?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="test">
<select id="findUserById" parameterType="int" resultType="cn.com.mybatis.po.User">
SELECT * FROM USER WHERE id=#{id}
</select>
<!-- 删除用户 -->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
<!-- 修改用户 -->
<update id="updateUserName" parameterType="cn.com.mybatis.po.User">
update user set username=#{username} where id=#{id}
</update>
</mapper>
会话工厂和会话
会话工厂—SqlSessionFactory类 会根据Resource资源信息加载对象,获取连接池信息,产生数据库交互会话实例类—SqlSession。
public class DataConnection {
private String resource="SqlMapConfig.xml";
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
public SqlSession getSqlSession() throws IOException{
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
sqlSession=sqlSessionFactory.openSession();
return sqlSession;
}
}
获取结果
SqlSession sqlSession=dataConn.getSqlSession();
User user=sqlSession.selectOne("test.findUserById",1);
System.out.println("姓名:"+user.getUsername());