# mybatis
mybatis实现原理
mybatis做的事情,首先要通过配置,构建SqlSessionFactory, SqlSessionFactory是构建SqlSession对象的Factory工厂
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory =
new JdbcTransactionFactory();
Environment environment =
new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(configuration);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
给用户的Mapper接口类创建动态代理,通过SqlSession.getMapper获取对应的Mapper类的Mapper对象, 这个Mapper对象是Mapper接口的动态代理类的对象。
try (SqlSession session = sqlSessionFactory.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
}
1
2
3
4
2
3
4
mybatis需要解析Mapper.xml文件,并且将对应的语句和Mapper接口的方法对应起来,还需要处理ResultMap这类的语法功能。
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
1
2
3
4
5
2
3
4
5
Mapper接口还支持使用注解配置sql语句
public interface BlogMapper {
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
}
1
2
3
4
2
3
4