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

  • 相关阅读:
    jQuery操作单选按钮(Radio)
    Django:DRF实现模糊搜索
    Django:实现导入功能,及下载模版
    python使用DES加密解密
    在线OCR识别
    bootstrap-table导出时存在bootstrap-switch按钮如何导出
    Django:解决时间显示格式含有T
    翻页时bootstrap-switch样式失效
    bootstraptable导出
    统计文件行数
  • 原文地址:https://www.cnblogs.com/2016024291-/p/8215154.html
Copyright © 2020-2023  润新知