MyBatis学习笔记2 getMapper

我会带着你远行 2024-03-30 14:24 177阅读 0赞

1、为什么要使用Dao代理来实现CURD?

观察笔记2可以发现、在传统Dao层开发模式中、Dao接口实现类并没有干什么实质性的工作,它仅仅就是通过SqlSession的相关API、根据用户提供的命名空间和id值、定位到映射mapper文件中相应的SQL语句,真正对DB进行操作的工作其实是由框架通过mapper中的SQL完成的。

  • 所以

MyBatis框架就抛开了Dao的实现类,直接定位到映射文件mapper中的相应SQL语句,对DB进行操作。这种对Dao的实现方式称为Mapper的动态代理方式Mapper动态代理方式无需程序员实现 Dao 接口。接口是由 MyBatis 结合映射文件自动生成的动态代理实现的。

2、在MyBatis中如何使用代理、直接找到对应的mapper文件?

  • 首先、将接口实现类删除。既然使用代理直接找到接口对应的mapper文件了,所以就不需要接口实现类了。
  • 通过SqlSession调用getMapper()即可获取指定接口的实现类对象。该方法的参数为指定Dao接口类的class值。

3、代码实现:

  • 直接对上一笔记的测试类代码进行修改、首先还是声明dao接口和sqlSession对象、然后在方法里给对象赋值、如下:

private UserInfoDao userInfoDao;
private SqlSession sqlSession;
@Before
public void init() throws IOException
{
this.sqlSession = MyBatisUtils.getSqlSession();
this.userInfoDao = this.sqlSession.getMapper(UserInfoDao.class);
}
@After
public void finish()
{
//关闭selectList,释放资源
this.sqlSession.close();
}

  • 增删改查修改如下:

@Test
public void selectAll()
{
List userList = userInfoDao.selectAll();
//循环输出集合中的结果
userList.forEach(x -> System.out.println(x));
}
@Test
public void selectUser()
{
UserInfo userInfo = this.userInfoDao.selectUser(2);
System.out.println(userInfo);
}

@Test
public void insert()
{
UserInfo userInfo = new UserInfo();
userInfo.setName(“王昭君”);
userInfo.setAge(16);
int result = this.userInfoDao.insert(userInfo);
sqlSession.commit();
System.out.println(result);
}

@Test
public void update()
{
UserInfo userInfo = new UserInfo();
userInfo.setId(2);
userInfo.setName(“李白”);
userInfo.setAge(20);
int result = this.userInfoDao.update(userInfo);
sqlSession.commit();
System.out.println(result);
}

@Test
public void delete()
{
int result = this.userInfoDao.delete(6);
sqlSession.commit();
System.out.println(result);
}
这样、通过代理的方式、直接找到对应的mapper文件里的标签和语句,更直接简单和简洁。

发表评论

表情:
评论列表 (有 0 条评论,177人围观)

还没有评论,来说两句吧...

相关阅读