mybatis入门之二、使用接口interface

2.1 为何使用接口 interface 来编程

**上一章用SqlSession实例来直接执行已映射的SQL语句:
session.selectOne(“com.yihaomen.mybatis.models.UserMapper.selectUserByID”, 1)
而更好的方法,是使用描述参数和SQL语句返回值的借口(eg:IUser)**

2.2 项目目录

项目结构

2.3 各个文件内容

* 接口interface*

package com.mybatis.dao;

import com.mybatis.models.User;

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

Test文件

import java.io.IOException;
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.mybatis.dao.IUser;
import com.mybatis.models.User;

public class Test {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;
    static {
        try {
            reader = Resources.getResourceAsReader("Configure.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        SqlSession sqlSession = sqlSessionFactory.openSession();;
        try {
            IUser iUser=sqlSession.getMapper(IUser.class);
            User user=iUser.selectUserByID(1);
            System.out.println("id:"+user.getId()+"  name"+user.getName()+"  phone:"+user.getPhone());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }


    }

}

其他都不需要改动,需要注意的是 User.xml里, mapper的 namespace=”com.mybatis.dao.IUser”,需要按实际改动, mapper.select id=”selectUserByID” 与接口中public User selectUserByID(int id);要一致
通过与第一章节的对比,会发现不同

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值