MyBatis的Mapper接口编程方式


使用传统的DAO开发方式虽然可以实现需求所需功能,但是采用这种方式在实现类中会出现大量重复代码,在方法中也需要指定映射文件中执行语句的id,并且不能保证编写时id正确性。为此,我们可以使用MyBatis提供的另外一种编程方式,即使用Mapper接口编程。

Mapper接口编程遵循以下规范

  1. Mapper接口的名称和对应的Mapper.xml映射文件的名称必须一样
  2. Mapper.xml文件中的namespace与Mapper.xml接口的类路径相同(即接口文件和映射文件需要放在同一包中)
  3. Mapper接口中的方法名和Mapper.xml中定义的每个执行语句的id相同
  4. Mapper接口中的方法的输入参数类型要和Mapper.xml中定义的每个sql的parameterType的类型相同
  5. Mapper接口方法中的输出参数类型要和Mapper.xml中定义的每个sql的resultType的类型相同

只要遵循了这些开发范式,MyBatis就可以自动生成Mapper接口实现类的代理对象,从而简化我们的开发。

Mapper接口编程示例

接下来使用Maven构建的项目,在项目中完成代码的编写,然后通过测试用例测试MyBatis是否自动生成Mapper接口实现类的代理对象。

编辑pom.xml文件

  1. 添加项目所需的依赖包
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <dependency>
            <groupId>ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant-launcher</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.22</version>
        </dependency>
    </dependencies>
  1. 指定xml、properties等资源文件路径
<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>true</filtering>
       </resource>
       <resource>
           <directory>src/main/resources</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>true</filtering>
       </resource>
   </resources>
    </build>

添加mybatis-config.xml配置文件

<?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>

    <environments default="mysql">
        <environment id="mysql">
            <!--使用JDBC事务管理-->
            <transactionManager type="JDBC"/>
            <!--数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/CustomerDao.xml" />
        <mapper resource="mapper/StudentDao.xml" />
    </mappers>
</configuration>

添加log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

添加工具类

package com.lwz.utils;

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 java.io.Reader;

/**
 * @author Lw中
 * @date 2020/5/8 11:03
 */
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory = null;
    // 初始化SqlSessionFactory对象
    static {
        try {
            // 使用MyBatis提供的Resources类加载mybatis的配置文件
            Reader reader =
                    Resources.getResourceAsReader("mybatis-config.xml");
            // 构建sqlSession的工厂
            sqlSessionFactory =
                    new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 获取SqlSession对象的静态方法
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }

}

添加pojo类和Mapper接口

pojo类

package com.lwz.entity;

import java.io.Serializable;

/**
 * (Student)实体类
 *
 * @author Lw中
 * @since 2020-05-01 18:06:10
 */
public class Student implements Serializable {
    private static final long serialVersionUID = -73864453563206708L;
    
    private Integer id;
    
    private Integer studentId;
    
    private String studentName;
    
    private Integer age;
    
    private String gender;
    
    private String className;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getStudentId() {
        return studentId;
    }

    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

}

Mapper接口

package com.lwz.dao;

import com.lwz.entity.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;

/**
 * (Student)表数据库访问层
 *
 * @author Lw中
 * @since 2020-05-11 09:36:11
 */
public interface StudentDao {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    Student queryById(Integer id);
}

添加Mapper映射文件

<?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.lwz.dao.StudentDao">

    <resultMap type="com.lwz.entity.Student" id="StudentMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="studentId" column="student_id" jdbcType="INTEGER"/>
        <result property="studentName" column="student_name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="gender" column="gender" jdbcType="VARCHAR"/>
        <result property="className" column="class_name" jdbcType="VARCHAR"/>
    </resultMap>

    <!--查询单个-->
    <select id="queryById" useCache="false" resultMap="StudentMap">
        select
          id, student_id, student_name, age, gender, class_name
        from mybatis.t_student
        where id = #{id}
    </select>
</mapper>    

添加测试用例

package com.lwz.test;

import com.lwz.dao.StudentDao;
import com.lwz.entity.Student;
import com.lwz.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;



/**
 * @author Lw中
 * @date 2020/5/8 10:51
 */
public class StudentTest {

    @Test
    public void testStudentDao() {

        // 通过工具类生成SqlSession对象
        SqlSession session = MybatisUtils.getSession();
        //第一次查询
        StudentDao studentDao = session.getMapper(StudentDao.class);
        Student student = studentDao.queryById(1);
        System.out.println(student.getStudentName());

    }
}

查看输出结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43894879/article/details/106069847