Mybatis 实现Mapper代理

Mapper代理好处:

  • 程序员只编写Mapper接口,不编写实现类。把实现类交给代理模式。由mybatis动态生成Mapper接口的代理类。

使用Mapper代理注意:4个一致

准备工作:mapper映射文件必须和mapper接口保存在一个目录中。

  • Mapper映射文件的名字和mapper接口的名字一致
  • Mapper映射文件中statementId的值,与mapper接口中对应的方法名一致
  • Mapper映射文件中statement的输入参数parameterType的类型,与mapper接口中对应方法的参数类型一致。
  • Mapper映射文件中statement的输出参数resultType的类型,与mapper接口中对应方法的返回值类型一致。

以查询表中所有数据为例

项目工程如下,并且导入相应jar包

tu1

数据库表sql如下

/*
SQLyog Ultimate v11.42 (64 bit)
MySQL - 8.0.20 
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

create table `user` (
    `id` int (4),
    `username` varchar (60),
    `password` varchar (60),
    `email` varchar (60),
    `sex` int (1),
    `realname` varchar (60)
); 
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('1','tom11','1234','159@qq.com','1','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('2','ppp','123','123@qq.com','0','ppp');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('4','kkk','258','258@qq.com','1','kkk');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('12','hhh','147','147@qq.com','0','hhh');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('15','jiae','156','138@qq.com','0','jiae');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('17','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('18','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('19','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('20','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('22','uuu','123','123@qq.com','1','uuu');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('24','uuu','123','123@qq.com','0','UUU');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('25','PPP','123','123@qq.com','1','PPP');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('26','YYY','123','123@qq.com','1','YYY');

1.编写USser实体类

package com.yin.mybatis.pojo;

public class User {

    private Integer id;
    private String username;
    private String password;
    private String email;
    private Integer sex;
    private String realname;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public String getRealname() {
        return realname;
    }
    public void setRealname(String realname) {
        this.realname = realname;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", sex="
                + sex + ", realname=" + realname + "]";
    }
    
    


    
}

2.编写Mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<properties resource="db.properties"/>

  <environments default="mysql">
    <environment id="mysql">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper class="com.yin.mybatis.mapper.UserMapper"/>
  </mappers>
</configuration>

3.编写UserMapper.java接口

package com.yin.mybatis.mapper;

import java.util.List;

import com.yin.mybatis.pojo.User;

public interface UserMapper {
  List<User>findAllUser();
}

4.UserMapper.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.yin.mybatis.mapper.UserMapper">

    <select id="findAllUser" resultType="com.yin.mybatis.pojo.User">
          <!-- id属性:是statement
                 输入参数: parameterType
                 输出参数:resultType
    #{}标识占位符 表示传递给当前的值是什么,吧输入参数的值设置给占位符
                 简单类型  基本类型和String
      -->
        
    select * from user
    </select>

</mapper>

5.编写Mybatis测试需要的工具类

package com.yin.mybatis.utils;

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;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    
    static {
    //InputStream inputStream = Resources.getResourceAsStream(resource);
    try {
        String resource ="SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }catch(IOException e) {
        e.printStackTrace();
        
      }
    }
    
       //获取SqlSession连接
       public static SqlSession getSession(){
           return sqlSessionFactory.openSession();
      }
    
    }

6.编写测试类

package com.yin.mybatis.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.yin.mybatis.mapper.UserMapper;
import com.yin.mybatis.pojo.User;
import com.yin.mybatis.utils.MybatisUtil;

public class UserTest2 {
    @Test
  public void testfindalluser() {
    SqlSession session =MybatisUtil.getSession();
    UserMapper mapper =session.getMapper(UserMapper.class);
    List<User> users =mapper.findAllUser();
    for(User user :users) {
        System.out.println(user);
    }
    session.commit();
    session.close();
    
  }
}

这样就可以查到数据啦。

tu2

最后修改:2021 年 05 月 10 日 09 : 04 PM
如果觉得我的文章对你有用,请随意赞赏