Mybatis_接口编程

Mybatis参考使用文档:http://www.mybatis.org/mybatis-3/zh/index.html

 

1.项目结构

2.新增EmployeeMapper.java接口代码

package com.atguigu.mybatis.dao;

import com.atguigu.mybatis.bean.Employee;

public interface EmployeeMapper {
    
    public Employee getEmpById(Integer id);

}

3.EmployeeMapper.xml改动

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapper">
<!-- 
namespace:名称空间;  指定接口全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值 

public Employee getEmpById();
-->
  <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}
  </select>
</mapper>
①namespace指定接口全名
②id指定接口方法

 3.MybatisTest.java

package com.atguigu.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
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 com.atguigu.mybatis.bean.Employee;
import com.atguigu.mybatis.dao.EmployeeMapper;

public class MybatisTest {
    
    private SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }
   
    @Test
    public void test02() throws IOException {
        /*1.创建sqlSessionFactory对象*/
        SqlSessionFactory sqlSessionFactory =getSqlSessionFactory();
        /*2.获取SqlSession对象*/
        SqlSession openSession= sqlSessionFactory.openSession();
        
        try {
            /*3.获取接口的实现对象*/
            EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
            //mapper为代理对象,执行增删改查
            Employee employee=mapper.getEmpById(1);
            
            System.out.println(employee);
        } finally {
            openSession.close();
        }
    }
}

 注:mybatis接口式编程不需要创建接口的实现类,只有接口就行

posted @ 2018-01-06 20:11  2016024291-董诗原  阅读(151)  评论(0编辑  收藏  举报