mybatis - XxxMapper.java接口中方法的参数 和 返回值类型,怎样在 XxxMapper.xml 中配置的问题

这个例子中的mybatis-config.xml文件,引用这个文件即可

实体类src/main/java/com.atguigu.pojo/Employee.java

java 复制代码
package com.atguigu.pojo;

public class Employee {
    private Integer id;

    private String name;

    private String plone;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPlone() {
        return plone;
    }

    public void setPlone(String plone) {
        this.plone = plone;
    }

    @Override
    public String toString() {
        return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", plone='" + plone + '\'' + '}';
    }
}

实体类对应的接口文件src/main/java/com.atguigu.mapper/EmployeeMapper.java

java 复制代码
package com.atguigu.mapper;

import com.atguigu.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface EmployeeMapper {

    根据id查看员工信息
    Employee queryById(Integer id);

    根据id删除员工信息(单个简单类型作为参数)
    int deleteById(Integer id);

    根据 plone 查询员工的信息(单个简单类型作为参数)
    List<Employee> queryByPlone(String plone);

    插入员工数据(单个实体对象作为参数)
    int insertEmp(Employee employee);

    传入多个简单类型的参数
    List<Employee> queryByNameAndPlone(@Param("xname") String name, @Param("xplone") String plone);

    传入 map类型的参数
    int insertEmpMap(Map data);

	-----------------------------------------------------------------------------
	
	查询工资高于传入值的员工姓名们
    List<String> queryNamesBySalary(@Param("salary") Double salary);
	
	返回集合类型,查询全部员工信息
    List<Employee> queryAll();

	返回map类型,查询城市的最高工资和平均工资
    Map<String, Object> selectEmpNameAndMaxSalary();

	自增长主键回显,自动提交事务
    int insertUser(Employee employee);


	-----------------------------------------------------------------------------
	
	mybatis自己维护非自增主键
	int insertEmployee(Employee employee);
	
	
	Employee queryByIdd(String tId);
}

EmployeeMapper.java接口文件对应的xml文件 src/main/resources/mappers/EmployeeMapper.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTO Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

namespace = 接口的权限定符
<mapper namespace="com.atguigu.mapper.EmployeeMapper">

    <select id="queryById" resultType="com.atguigu.pojo.Employee">
        select id, name, plone from my_user where id = #{id}
    </select>


    场景1:传入参数,是单个简单类型,key的值随便写,一般推荐使用参数名
    <delete id="deleteById">
        <!-- key的值可以这样写:delete from my_user where id = #{ergouzi} -->
        <!-- 推荐还是使用参数名,如下 -->
        delete from my_user where id = #{id}
    </delete>


    <select id="queryByPlone" resultType="com.atguigu.pojo.Employee">
        select id, name, plone from my_user where plone = #{plone}
    </select>


    场景2:传入的参数,是单个实体对象,key的值怎么写呢? key = (实体类的每个)属性名,即可
    <insert id="insertEmp">
        insert into my_user (name, plone) values (#{name},#{plone});
    </insert>


    场景3:传入多个简单类型的参数,key的值怎么写呢?
           * 方案1:使用@param注解(推荐使用注解)
           * 方案2:mybatis的默认机制,如下:
                    形参arg0, arg1 ... , argn 从左到右依次对应的key值是 arg0, arg1 ... , argn
    <select id="queryByNameAndPlone" resultType="com.atguigu.pojo.Employee">
        select id, name, plone from my_user where plone = #{xplone} and name = #{xname}
    </select>


    场景4:传入的是 map类型 的参数,key的值怎么写呢? key = map的key,即可
    <insert id="insertEmpMap">
        insert into my_user (name, plone) values (#{name},#{plone});
    </insert>

---------------------------------------------------------------------------------------------------
	当,返回值是,集合类型,时,resultType 怎样指定? 
		这里就用到了MyBatis中的别名
        切记:
        	返回值是集合时,resultType不需要指定集合类型,只需要指定泛型即可,
        为什么呢?
            因为 mybatis 底层是 ibatis,
                虽然,selectOne是查询单个,selectList是查询集合,
                但是,selectOne 其实也是调用的 selectList,
                只不过, selectOne的时候,取的是selectList里面的第一个值而已
            所以,返回值是集合时,resultType不需要指定集合类型,只需要指定泛型即可。
    <select id="queryNamesBySalary" resultType="string">
        select name from my_user where salary > #{salary}
    </select>



	因为,在mybatis-config.xml文件种配置了别名,下面这一行
			<typeAliases> <package name="com.atguigu.pojo"/> </typeAliases>
    所以,这里可以 resultType="employee",而不用 resultType="com.atguigu.pojo.Employee" 了
    <select id="queryAll" resultType="employee">
        select * from my_user
    </select>



	什么时候,返回map?
        当没有实体类可以使用接值的时候,可以使用map接受数据,
        map的key,对应,查询的列名
        map的value,对应,查询的值
    <select id="selectEmpNameAndMaxSalary" resultType="map">
        SELECT
	        `name` 姓名,
	        salary 工资,
	        (SELECT AVG(salary) FROM my_user) 城市平均工资
        FROM
	        my_user
        WHERE
	        salary = (SELECT MAX(salary) FROM my_user)
    </select>



	自增长主键回显,自动提交事务
        获取自增长的主键,可以使用:
            useGeneratedKeys="true",代表,我们想要获取数据库自增的主键id
            keyColumn="id",代表,数据库表的主键列的值
            keyProperty="id",代表,接收主键列值的实体类的属性
    <insert id="insertUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        insert into my_user (name, plone) values(#{name}, #{plone});
    </insert>


---------------------------------------------------------------------------------------------------

	mybatis自己维护非自增主键
    <insert id="insertEmployee">
		让mybatis帮我们维护非自增的主键,我们就不在MybatisTest.java中编写相关的代码了
               order="BEFORE" 或者 "AFTER",意思是,在sql语句之前执行,还是之后执行
               resultType,表示,返回值类型
               keyProperty,表示,查询的结果,给实体类中的哪个属性

		这个 selectkey 就相当于 MybatisTest.java文件中的,下面这几行代码
                自己维护主键,使用uuid,这里replaceAll操作,是去掉uuid的中划线
                String id = UUID.randomUUID().toString().replaceAll("-", "");
                employee.settId(id);
        <selectKey order="BEFORE" resultType="string" keyProperty="tId">
            SELECT REPLACE(UUID(),'-','')
        </selectKey>
        insert into my_user (t_id, t_name) values(#{tId}, #{tName})
    </insert>



    列名 和 属性名 不一致如何解决?
            方案1:别名:select t_id tId, t_name tName from teacher where t_id = #{tId}

            方案2:开启mybatis的驼峰式映射配置: <setting name="mapUnderscoreToCamelCase" value="true"/>
                        会自动把 t_id 映射成 tId

            方案3:使用resultMap自定义映射,注意:resultType 和 resultMap 二选一!
                        resultType按照规则自动映射,按照是否开启驼峰式映射。自己映射属性和列名,只能映射一层结构
                        resultMap可以深层次的映射哦!!!
                        
                        例如:
						    声明 resultMap标签,定义自己的映射规则
						                id:是某个resultMap的唯一标识,
						                    用于在<select id="queryById" resultMap="id">中,
						                    确定这个select使用哪个resultMap
						                result:普通列的映射关系
    <resultMap id="tMap" type="teacher">
        <id column="t_id" property="tId" />
        <result column="t_name" property="tName" />
    </resultMap>
    <select id="queryByIdd" resultMap="tMap">
        select * from teacher where t_id = #{tId}
    </select>

	


</mapper>

测试文件src/test/java/com.atguigu.MybatisTest.java

java 复制代码
package com.atguigu.test;

import com.atguigu.mapper.EmployeeMapper;
import com.atguigu.pojo.Employee;
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.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;

public class MybatisTest {
    @Test
    public void test_01() throws IOException {
       
        1、读取外部配置文件(mybatis-config.xml)
           使用MyBatis提供的Resources类,读取名为mybatis-config.xml的配置文件。
        InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");


        2、创建sqlSessionFactory
              使用SqlSessionFactoryBuilder根据配置文件构建SqlSessionFactory对象。
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);


        3、根据sqlSessionFactory创建sqlSession对象【自动开启JDBC】【自动开启事务,但不会自动提交事务,需要sqlSession.commit()手动开启】
                或者使用 sqlSessionFactory.openSession(true)【会自动开启事务,自动提交事务,不需要写sqlSession.commit()】
        SqlSession sqlSession = sqlSessionFactory.openSession();


         4、使用SqlSession的getMapper()方法,获取EmployeeMapper接口的代理对象,并且调用具体的SQL方法
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);


        调用EmployeeMapper接口的queryById()方法,传入参数1,执行查询操作,并将结果赋值给employee对象。
        Employee employee = mapper.queryById(1);
        System.out.println(employee);
        
		// 因为我们在 EmployeeMapper.xml文件中使用了 selectkey 让mybatis帮我们维护了主键,所以这里可以注掉了
        // 自己维护主键,使用uuid,这里replaceAll操作,是去掉uuid的中划线
        // String id = UUID.randomUUID().toString().replaceAll("-", "");
        // employee.settId(id);


        5、提交事务(非DQL)和释放资源
             sqlSession.commit():提交事务,但是在这个查询操作的上下文中,commit是不必要的,因为查询操作不需要提交事务。
             通常,只有DML(如INSERT、UPDATE、DELETE)操作才需要提交事务。
        sqlSession.commit();
        sqlSession.close();
    }
}
相关推荐
AI人工智能+电脑小能手7 分钟前
【大白话说Java面试题】【Java基础篇】第22题:HashMap 和 HashSet 有哪些区别
java·开发语言·哈希算法·散列表·hash
juniperhan21 分钟前
Flink 系列第21篇:Flink SQL 函数与 UDF 全解读:类型推导、开发要点与 Module 扩展
java·大数据·数据仓库·分布式·sql·flink
ID_1800790547322 分钟前
Python 实现亚马逊商品详情 API 数据准确性校验(极简可用 + JSON 参考)
java·python·json
c++之路42 分钟前
C++23概述
java·c++·c++23
专注API从业者2 小时前
Open Claw 京东商品监控选品实战:一键抓取、实时监控、高效选品
java·服务器·数据库
摇滚侠2 小时前
DBeaver 导入数据库 导入 SQL 文件 MySQL 备份恢复
java·数据库·mysql
keep one's resolveY2 小时前
SpringBoot实现重试机制的四种方案
java·spring boot·后端
天空属于哈夫克33 小时前
企业微信API常见的错误和解决方案
java·数据库·企业微信
摇滚侠4 小时前
VMvare 虚拟机 Oracle19c 安装步骤,远程连接 Oracle19c,百度网盘安装包
java·oracle
梁萌4 小时前
idea报错找不到XX包的解决方法
java·intellij-idea·启动报错·缺少包