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

本文主要是介绍mybatis - XxxMapper.java接口中方法的参数 和 返回值类型,怎样在 XxxMapper.xml 中配置的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

实体类src/main/java/com.atguigu.pojo/Employee.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;}@Overridepublic String toString() {return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", plone='" + plone + '\'' + '}';}
}

实体类对应的接口文件src/main/java/com.atguigu.mapper/EmployeeMapper.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 version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//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) 城市平均工资FROMmy_userWHEREsalary = (SELECT MAX(salary) FROM my_user)</select>自增长主键回显,自动提交事务获取自增长的主键,可以使用:useGeneratedKeys="true",代表,我们想要获取数据库自增的主键idkeyColumn="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使用哪个resultMapresult:普通列的映射关系<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


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 {@Testpublic 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、使用SqlSessiongetMapper()方法,获取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(如INSERTUPDATEDELETE)操作才需要提交事务。sqlSession.commit();sqlSession.close();}
}

这篇关于mybatis - XxxMapper.java接口中方法的参数 和 返回值类型,怎样在 XxxMapper.xml 中配置的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/948527

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

mybatis的整体架构

mybatis的整体架构分为三层: 1.基础支持层 该层包括:数据源模块、事务管理模块、缓存模块、Binding模块、反射模块、类型转换模块、日志模块、资源加载模块、解析器模块 2.核心处理层 该层包括:配置解析、参数映射、SQL解析、SQL执行、结果集映射、插件 3.接口层 该层包括:SqlSession 基础支持层 该层保护mybatis的基础模块,它们为核心处理层提供了良好的支撑。

Zookeeper安装和配置说明

一、Zookeeper的搭建方式 Zookeeper安装方式有三种,单机模式和集群模式以及伪集群模式。 ■ 单机模式:Zookeeper只运行在一台服务器上,适合测试环境; ■ 伪集群模式:就是在一台物理机上运行多个Zookeeper 实例; ■ 集群模式:Zookeeper运行于一个集群上,适合生产环境,这个计算机集群被称为一个“集合体”(ensemble) Zookeeper通过复制来实现

CentOS7安装配置mysql5.7 tar免安装版

一、CentOS7.4系统自带mariadb # 查看系统自带的Mariadb[root@localhost~]# rpm -qa|grep mariadbmariadb-libs-5.5.44-2.el7.centos.x86_64# 卸载系统自带的Mariadb[root@localhost ~]# rpm -e --nodeps mariadb-libs-5.5.44-2.el7