使用mybatis以接口开发方式编程

一、先在\src\main\java下创建一个包,包名为com.hgc.inter,然后在该包下创建UserInterface.java,该文件代码如下

package com.hgc.inter;

import com.hgc.pojo.User;
import org.apache.ibatis.annotations.Select;

/**
 * Created by 47500 on 2017/9/7.
 */
public interface UserInterface {
    @Select("SELECT * FROM user WHERE id=#{id}")
    public User selectUserByID(int id);
}

二、在src\main下创建test文件夹,然后在该文件夹下创建UserTest.java,代码如下

import com.hgc.inter.UserInterface;
import com.hgc.pojo.User;
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 org.junit.Test;

import java.io.Reader;



/**
 * Created by 47500 on 2017/9/7.
 */
public class UserTest {
    /**
     * 根据接口及注释获取数据
     */
    @Test
    public void findByIdByInter() throws Exception{
        String resource ="mybatis-config.xml";
        Reader reader = null;
        reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //注册该接口
        sqlSessionFactory.getConfiguration().addMapper(UserInterface.class);
        //
        SqlSession session = sqlSessionFactory.openSession();
        UserInterface userInterface = session.getMapper(UserInterface.class);
        User user = userInterface.selectUserByID(1);
        System.out.println(user.getName());
    }
}

三、以单元测试的方式运行程序
mybatis的环境搭建参考http://blog.csdn.net/qq_31154765/article/details/77647854

你可能感兴趣的:(mybatis,java)