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

  • 相关阅读:
    Commons.net FTPClient 上传文件
    C盘空间不够,清除VS下的 Font Cache
    Redis 密码设置
    Window bat expdp 定时任务逻辑备份 定时删除N天前的旧文件
    Windows下修改Oracle默认的端口1521
    Intellij idea 乱码问题(英文操作系统)
    给VMware下的Linux扩展磁盘空间(以CentOS6.3为例)转
    TortoiseSVN and TortoiseGit 版本控制图标不见了
    R语言中字符串的拼接操作
    SparkR:数据科学家的新利器
  • 原文地址:https://www.cnblogs.com/2016024291-/p/8215154.html
Copyright © 2020-2023  润新知