MyBatis如何使用(二)


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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3