服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - MyBatis如何使用(二)

MyBatis如何使用(二)

2020-05-31 13:16迷茫中守候 Java教程

这篇文章主要介绍了MyBatis如何使用(二)的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下

前边阐述了如何在java项目中使用mybatis,我们使用的是映射文件的方式,在获得具体的数据操作方法时需要传入映射文件中namespace+“.”方法名称,这种方式有时候会感觉很不爽,很麻烦。我们在开发中不是常说要面向接口变成吗,mybatis也支持接口,下面在前面的例子的基础上做相应修改。

前面的例子的环境及映射文件均保持不变,如下是我的映射文件,

?
1
2
3
4
5
6
7
8
9
10
11
12
<mapper namespace="com.cn.inter.IMessageOperation">
<select id="selectUserByID" parameterType="int" resultType="com.cn.imooc.entity.Message">
select * from `message` where id = #{id}
</select>
<select id="selectMessages" resultType="Message">
select id,
command,
description,
comment
from message;
</select>
</mapper>

我们可以看到里边有namespace为com.cn.inter.ImessageOperation,现在我们创建这样一个包,com.cn.inter,在此包中创建接口IMessageOperation,接口中有一个方法,方法的签名为:public Message selectUserByID(Integer id);

我们创建的接口和映射文件做了一致对应,包括了方法名、返回值、参数列表。下面看测试方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.cn.test;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.cn.imooc.entity.Message;
import com.cn.inter.IMessageOperation;
public class MyTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Reader reader;
SqlSession sqlSession=null;
try{
//从类路径下(src)读取mybatis配置文件
reader=Resources.getResourceAsReader("Configuration.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
sqlSession=sqlSessionFactory.openSession();
//获得IMessageOperation接口
IMessageOperation imo=sqlSession.getMapper(IMessageOperation.class);
//调用接口的方法返回查询结果
Message message=imo.selectMessageByIdI(new Integer(3));
System.out.println(message);
}
catch(Exception e){
e.printStackTrace();
}finally{
//如果sqlSession不为空,则关闭
if(null!=sqlSession)
sqlSession.close();
}
}
}

我们可以看到测试方法中调用数据操作的方法发生了变化,我们是先获得一个IMessageOperation的接口,然后调用其selectMessageByID方法,最后得到结果。可以感觉到比上一篇中的方式更加简单了,也更符合我们日常的编码规范了。

综合这两篇内容中的方式,使用任何一种都是可以的,只是两种不同的方式而已,我个人更倾向于后者。

以上所述是小编给大家介绍的MyBatis如何使用(二)的相关资料,非常不错,具有参考借鉴价值,希望对大家有所帮助!

原文链接:http://www.cnblogs.com/teach/archive/2016/07/23/5699816.html

延伸 · 阅读

精彩推荐