37

图解源码:MyBatis 的 Mapper 原理

 5 years ago
source link: https://mp.weixin.qq.com/s/Ki1f_mkoOkPMQiGbJWu4Sw?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

提到看源码,很多同学内心的恐惧的,其实这个从人性的角度来说是非常正常的,因为人们对未知的事物,都是非常恐惧的,其次,你内心可能始终觉得,好像不会原理也还是能工作啊,你的潜意识里没有强烈的欲望.从阅读源码的经历来说,Java三大框架SSM中,Mybatis的源码是最适合入门的.

简单使用

这是一个简单的Mybatis保存对象的例子

 1@Test
2public void testSave() throws Exception {
3 //创建sessionFactory对象
4 SqlSessionFactory sf = new SqlSessionFactoryBuilder().
5 build(Resources.getResourceAsStream("mybatis-config.xml"));
6 //获取session对象
7 SqlSession session = sf.openSession();
8 //创建实体对象
9 User user = new User();
10 user.setUsername("toby");
11 user.setPassword("123");
12 user.setAge(23);
13 //保存数据到数据库中
14 session.insert("com.toby.mybatis.domain.UserMapper.add", user);
15 //提交事务,这个是必须要的,否则即使sql发了也保存不到数据库中
16 session.commit();
17 //关闭资源
18 session.close();
19}
1<mapper namespace="com.toby.mybatis.domain.UserMapper">
2 <!--#{}在传入的对象中找对应的属性值-->
3 <!--parameterType传入的参数是什么类型-->
4 <insert id="add" parameterType="com.toby.mybatis.domain.User">
5 INSERT INTO USER (username,password,age) VALUES (#{username},#{password},#{age})
6 </insert>
7</mapper>

引出主题

但是在实际中,我们都不是这样操作的,我们是通过Mapper接口,调用接口方法,就能实现CRUD操作,那么关键是,这个接口究竟做了什么事,才是我们关心的.

只要把下面这段代码究竟发生了什么事弄明白,就明白,这个Mapper接口究竟做了什么事.

1public void testGetObject() throws Exception {
2 SqlSession session = MybatisUtil.openSession();
3
4 UserMapper mapper = session.getMapper(UserMapper.class);
5 User user = mapper.get(5L);
6
7 System.out.println(user);
8 session.close();
9}

1public interface UserMapper {
2
3 public void add(User user);
4 public User get(Long id);
5}

流程图

但是我认为,一张流程图和时序图就看明白这期间所发生的事

Jbi6vay.jpg!web

BzumMvq.jpg!web

I7JJ7bV.gif


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK