MyBatis实现Mapper配置并查询数据

MyBatis实现Mapper配置并查询数据

  • 什么是Mapper
  • 创建目录
  • 注解方式使用Mapper
    • 代码实现
      • 导包
      • 创建mybatis-config.xml配置文件
      • 新建UserMapper.java类
      • 创建UserTest.java测试类
      • 运行结果
  • XML方式使用Mapper
    • 代码实现
      • UserMapper.java
      • 在资源文件夹下新建mapper包,并在其下新建名为UserMapper的XML文件
      • UserTest.java
  • select-resultMap
    • UserMapper.xml
    • 创建User实体类:User.java
    • UserMapper.java
    • UserTest.java
      • 运行结果

什么是Mapper

MyBatis工程搭建 中我们使用的是JDBC 方式执行 SQL 语句连接数据库,但在实际应用中是不会选择 JDBC 来执行 SQL 的,MyBatis 提供了 Mapper 作为 Java 方法和 SQL 语句之间的桥梁,来帮助我们更好地去使用 SQL
Java 接口方法与 SQL 语句以及 mapper 之间的关系如下图所示:
在这里插入图片描述

创建目录

MyBatis实现Mapper配置并查询数据_第1张图片

注解方式使用Mapper

代码实现

导包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>zhangyichen4</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.3.0-alpha5</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

创建mybatis-config.xml配置文件

添加对应的mapper配置

<?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="development">
        <environment id="development">
            <!-- 事务管理器 -->
            <transactionManager type="JDBC"/>
            <!-- 数据源 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/javaweb?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="362522"/>
            </dataSource>
        </environment>
    </environments>
    <!-- mapper配置 -->
    <mappers>
        <mapper class="mapper.UserMapper"/>
    </mappers>
</configuration>

新建UserMapper.java类

package mapper;

import entity.User;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    /**
     * 通过用户id查询用户名称
     *
     * @param id 用户id
     * @return 用户名称
     */
    @Select("SELECT username FROM user WHERE id = #{id}")

}

创建UserTest.java测试类

import entity.User;
import mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.sql.SQLException;

@SuppressWarnings({"Duplicates"})
public class UserTest {
    public static void main(String[] args) throws IOException , SQLException{
        // 读取配置文件
        InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
        // 得到 SqlSessionFactory 核心类
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        // 开始一个 sql 会话
        SqlSession session = sqlSessionFactory.openSession();
        // 得到 mapper
        UserMapper mapper = session.getMapper(UserMapper.class);

        // 调用注解的SQL
        String username = mapper.selectUsernameById(1);
        System.out.println("username: " + username);

        // 关闭会话
        session.close();
    }
}

运行结果

MyBatis实现Mapper配置并查询数据_第2张图片

XML方式使用Mapper

XML方式是更加强大的一种使用方式,虽然它没有注解那么方便,但是功能更强、更易维护,是 MyBatis 官方推荐的一种方式

代码实现

在 UserMapper 接口中,我们再新增一个方法selectUserAgeById,该方法的作用是通过用户id查询用户年龄

UserMapper.java

package mapper;

import entity.User;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    /**
     * 通过用户id查询用户名称
     *
     * @param id 用户id
     * @return 用户名称
     */
    @Select("SELECT username FROM user WHERE id = #{id}")
    String selectUsernameById(Integer id);

    /**
     * 通过用户id查询用户年龄
     *
     * @param id 用户id
     * @return 用户年龄
     */
    Integer selectUserAgeById(Integer id);

在资源文件夹下新建mapper包,并在其下新建名为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="mapper.UserMapper">
    <select id="selectUserAgeById" resultType="java.lang.Integer">
        SELECT age FROM user WHERE id = #{id}
    </select>
</mapper>

select 标签中有两个必填属性:
id:对应接口的方法名,即 selectUserAgeById,通过它 MyBatis 才能将二者对应起来
resultType:对应 SQL 语句的返回类型,与接口方法的返回值相同,有时会用到resultMap

UserTest.java

import entity.User;
import mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.sql.SQLException;

@SuppressWarnings({"Duplicates"})
public class UserTest {
    public static void main(String[] args) throws IOException , SQLException{
        // 读取配置文件
        InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
        // 得到 SqlSessionFactory 核心类
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        // 开始一个 sql 会话
        SqlSession session = sqlSessionFactory.openSession();
        // 得到 mapper
        UserMapper mapper = session.getMapper(UserMapper.class);

        // 调用注解的SQL
        String username = mapper.selectUsernameById(1);
        System.out.println("username: " + username);

        // 调用XML的SQL
        Integer age = mapper.selectUserAgeById(1);
        System.out.println("age: " + age);


        // 关闭会话
        session.close();
    }
}

MyBatis实现Mapper配置并查询数据_第3张图片

select-resultMap

UserMapper.xml

新增 selectUserById 标签,该 select 标签的作用是:通过id查询用户

<?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="mapper.UserMapper">
    <select id="selectUserAgeById" resultType="java.lang.Integer">
        SELECT age FROM user WHERE id = #{id}
    </select>
    <select id="selectUserById" resultMap="userMap">
        SELECT * FROM user WHERE id = #{id}
    </select>
    <resultMap id="userMap" type="entity.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="age" column="age"/>
        <result property="score" column="score"/>
    </resultMap>
</mapper>

创建User实体类:User.java

package entity;

public class User {
    private Integer id;
    private String username;
    private Integer age;
    private Integer score;

    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 Integer getAge() {
        return age;
    }

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

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}

UserMapper.java

package mapper;

import entity.User;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    /**
     * 通过用户id查询用户名称
     *
     * @param id 用户id
     * @return 用户名称
     */
    @Select("SELECT username FROM user WHERE id = #{id}")
    String selectUsernameById(Integer id);

    /**
     * 通过用户id查询用户年龄
     *
     * @param id 用户id
     * @return 用户年龄
     */
    Integer selectUserAgeById(Integer id);

    /**
     * 通过用户id查询用户信息
     *
     * @param id
     * @return
     */
    User selectUserById(Integer id);
}

UserTest.java

import entity.User;
import mapper.UserMapper;
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.IOException;
import java.io.InputStream;
import java.sql.SQLException;

@SuppressWarnings({"Duplicates"})
public class UserTest {
    public static void main(String[] args) throws IOException , SQLException{
        // 读取配置文件
        InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
        // 得到 SqlSessionFactory 核心类
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        // 开始一个 sql 会话
        SqlSession session = sqlSessionFactory.openSession();
        // 得到 mapper
        UserMapper mapper = session.getMapper(UserMapper.class);

        // 调用注解的SQL
        String username = mapper.selectUsernameById(1);
        System.out.println("username: " + username);

        // 调用XML的SQL
        Integer age = mapper.selectUserAgeById(1);
        System.out.println("age: " + age);

        // 调用通过用户id查询用户信息的方法
        User user = mapper.selectUserById(1);
        System.out.println(user);

        // 关闭会话
        session.close();
    }
}


运行结果

MyBatis实现Mapper配置并查询数据_第4张图片

你可能感兴趣的:(java,mybatis)