当前位置: 移动技术网 > IT编程>开发语言>Java > MyBatis如何使用(二)

MyBatis如何使用(二)

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

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

<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);

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

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如何使用(二)的相关资料,非常不错,具有参考借鉴价值,希望对大家有所帮助!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网