码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis实战教程(mybatis in action)之二:以接口的方式编程

时间:2016-12-30 12:54:18      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:ima   color   clip   文字   content   目录   msu   好的   bottom   

前面一章,已经搭建好了eclipse,mybatis,mysql的环境,并且实现了一个简单的查询。请注意,这种方式是用SqlSession实例来直接执行已映射的SQL语句:
session.selectOne("com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1)
其实还有更简单的方法,而且是更好的方法,使用合理描述参数和SQL语句返回值的接口(比如IUserOperation.class),这样现在就可以至此那个更简单,更安全的代码,没有容易发生的字符串文字和转换的错误.下面是详细过程:

在src_user源码目录下建立 com.yihaomen.mybatis.inter 这个包,并建立接口类 IUserOperation , 内容如下:
技术分享 程序代码

package com.yihaomen.mybatis.inter;
import com.yihaomen.mybatis.model.User;

public interface IUserOperation {    
    public User selectUserByID(int id);
    
}

请注意,这里面有一个方法名 selectUserByID 必须与 User.xml 里面配置的 select 的id 对应(<select id="selectUserByID")

重写测试代码
技术分享 程序代码

public static void main(String[] args) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation=session.getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(1);
            System.out.println(user.getUserAddress());
            System.out.println(user.getUserName());
        } finally {
            session.close();
        }
    }

整个工程结构图现在如下:
技术分享

运行这个测试程序,就可以看到结果了。



mybatis实战教程(mybatis in action)之二:以接口的方式编程

标签:ima   color   clip   文字   content   目录   msu   好的   bottom   

原文地址:http://www.cnblogs.com/jeffen/p/6236302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!