zoukankan      html  css  js  c++  java
  • 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接口式编程不需要创建接口的实现类,只有接口就行

  • 相关阅读:
    Rafy 框架
    巧用拦截器:高效的扩展点设计
    Rafy 框架
    Rafy 框架
    Rafy 框架
    Rafy 框架-发布网页版用户手册
    Rafy 领域实体框架
    基金投资方法札记
    股票、基金投资方案总结
    BaaS API 设计规范
  • 原文地址:https://www.cnblogs.com/2016024291-/p/8215154.html
Copyright © 2011-2022 走看看