职业菜鸟☆ 2022-05-29 20:01 采纳率: 75%
浏览 214
已结题

mybatis通过Map接口传递参数为null,但不报错

问题遇到的现象和发生背景

学习mybatis时,通过Map接口传递参数,但Map传不过来显示为null。

问题相关代码,请勿粘贴截图

application.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 加载数据库配置文件 -->
    <context:property-placeholder location="classpath:config/jdbc.properties" />
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 最大连接数 -->
        <property name="maxTotal" value="${jdbc.maxTotal}" />
        <!-- 最大空闲连接数 -->
        <property name="maxIdle" value="${jdbc.maxIdle}" />
        <!-- 初始化连接数 -->
        <property name="initialSize" value="${jdbc.initialSize}" />
    </bean>
    <!-- 添加事务支持 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="txManager" />
    <!-- 配置MyBatis工厂,同时指定数据源,并与MyBatis完美整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- configLocation的属性值为MyBatis的核心配置文件 -->
        <property name="configLocation" value="classpath:config/mybatis-config.xml" />
    </bean>
    <!--Mapper代理开发,MapperScannerConfigurer将包中所有接口自动装配为MyBatis映射接口Mapper的实现类的实例(映射器),所有映射器都被自动注入SqlSessionFactory实例,同时扫描包中SQL映射文件(.xml) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- mybatis-spring组件的扫描器,basePackage:属性可以包含多个包名,多个包名之间可以用逗号或分号隔开 -->
        <property name="basePackage" value="com.mybatis.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>

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>
    <settings>
        <setting name="logImpl"  value="LOG4J"/>
    </settings>
    <!-- 起别名 -->
    <typeAliases>
        <package name="com.mybatis.po"/>
    </typeAliases>
</configuration>

jdbc.properties文件内容如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springtest?characterEncoding=utf8
jdbc.username=root
jdbc.password=root@LC6
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

springmvc.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd        
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
    <context:component-scan base-package="com.mybatis.controller"/> 
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            id="internalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/jsp/" />
       <property name="suffix" value=".jsp" />
      </bean>
      <mvc:annotation-driven />
    <!-- 允许WebContent/static目录下所有文件可见 -->
    <mvc:resources location="/static/" mapping="/static/**"></mvc:resources>   
</beans>

log4j.properties文件内容如下:

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.mybatis.mapper=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

MyUser文件内容如下:

package com.mybatis.po;

//  springtest 数据库中user表的持久化类
public class MyUser {
    private Integer uid;//主键
    private String uname;
    private String usex;
    public Integer getUid() {
        return uid;
    }
    public void setUid(Integer uid) {
        this.uid = uid;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getUsex() {
        return usex;
    }
    public void setUsex(String usex) {
        this.usex = usex;
    }
    @Override
    public String toString() {//为了方便查看结果,重写了toString方法
        return "MyUser [uid=" + uid + ", uname=" + uname + ", usex=" + usex + "]";
    }
}

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.mybatis.mapper.UserMapper">
<!-- 查询姓张的女性用户 -->
    <select id="testMapSelect" resultType="MyUser" parameterType="map">
        select * from user 
        where uname like concat("%",#{uname},"%") 
        and usex = #{usex}
    </select>
</mapper>

UserMapper.java接口文件内容如下:

package com.mybatis.mapper;

import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.mybatis.po.MapUser;
import com.mybatis.po.MyUser;

@Repository
public interface UserMapper {
    public List<MyUser> testMapSelect(Map<String, Object> param);
}

TestController.java文件内容如下:

package com.mybatis.controller;
import java.util.HashMap;

@Controller
public class TestController {
    @Autowired
    private UserMapper userMapper;
@RequestMapping("/testMapSelect")
    public String testMapSelect(Model model) {
        //查询所有姓张的女性用户
        Map<String, Object> map = new HashMap<>();
        map.put("u_name", "张");
        map.put("U_sex", "女");
        System.out.println(map);
        List<MyUser> unameAndUsexList = userMapper.testMapSelect(map);
        model.addAttribute("unameAndUsexList",unameAndUsexList);
        return "showUnameAndUsexUser";
    }
}

showUnameAndUsexUser.jsp文件内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="static/css/bootstrap.min.css" />
</head>
<body>
    <div class="container">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">张姓女性用户列表</h3>
            </div>
            <div class="panel-body">
                <div class="table table-responsive">
                    <table class="table table-bordered table-hover">
                        <tbody class="text-center">
                            <tr>
                                <th>用户ID</th>
                                <th>姓名</th>
                                <th>性别</th>
                            </tr>
                            <c:forEach items="${unameAndUsexList}" var="user">
                                <tr>  
                                    <td>${user.uid}</td>
                                    <td>${user.uname}</td>
                                    <td>${user.usex}</td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

数据库截图:

img

运行结果及报错内容

img

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 13 in XML document from class path resource [config/springmvc.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 27; 元素 "mvc:annotation-driven" 的前缀 "mvc" 未绑定。

我的其他程序执行过程中这个报错不影响,但我观看的学习视频中没有报错,不知道是不是这个报错影响的

我的解答思路和尝试过的方法

我尝试过把select标签中的parameterType改成过Map,我以为是大写小问题,也没有变化;我还把userMapper接口的方法的参数改成中Map<String,String>,还是传递不过来map的值

我想要达到的结果

map能传递值,并且能在web页面展示出来,求各位帮帮忙!

  • 写回答

1条回答 默认 最新

  • 拾光师 2022-05-29 23:18
    关注
     Map<String, Object> map = new HashMap<>();
            map.put("u_name", "张");
            map.put("U_sex", "女");
            System.out.println(map);
            List<MyUser> unameAndUsexList = userMapper.testMapSelect(map);
    

    你在map中传入的key是u_name和U_sex,所以你在mapper.xml中使用也要使用对应的key
    所以应该是

    <mapper namespace="com.mybatis.mapper.UserMapper">
    <!-- 查询姓张的女性用户 -->
        <select id="testMapSelect" resultType="MyUser" parameterType="map">
            select * from user 
            where uname like concat("%",#{u_name},"%") 
            and usex = #{U_sex}
        </select>
    </mapper>
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 6月7日
  • 已采纳回答 5月30日
  • 创建了问题 5月29日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来