首页 > 其他分享 >mybatis使用resultMap获取不到值的解决方案

mybatis使用resultMap获取不到值的解决方案

时间:2023-02-08 18:36:08浏览次数:39  
标签:name 解决方案 resultMap public pwd mybatis import id String

目录
  • mybatis resultMap获取不到值
    • 问题描述
    • 原因及解决方法
  • Mybatis 从数据库中获取值为null ResultMap
    • 要解决的问题:属性名和字段名不一致
    • 解决方法

 

mybatis resultMap获取不到值


    <resultMap type="com.fc.model.Shop" id="employeeMap">
        <id column="shop_id" property="shopId"></id>
        <result column="name" property="name"></result>
    </resultMap> 
 
    <!-- 获取店员列表 -->
    <select id="getEmployeeList" parameterType="java.util.Map" resultMap="employeeMap">
    	select *, (  
		    6371 * acos (  
		      cos ( radians( #{latitude} ) )  
		      * cos( radians( s.latitude ) )  
		      * cos( radians( s.longitude ) - radians( #{longitude} ) )  
		      + sin ( radians( #{latitude} ) )  
		      * sin( radians( s.latitude ) )  
		    )  
		) as distance
    	from
    	<include refid="table_name"></include> as e
    	join <include refid="table_name_shop"></include> as s
    	on e.shop_id = s.shop_id
    	limit #{offset, jdbcType=INTEGER}, #{limit, jdbcType=INTEGER}
    </select>

 

问题描述

前端获取的接口没有得到distance字段

 

原因及解决方法

在实体中没有声明distance字段,在实体中声明

 

Mybatis 从数据库中获取值为null ResultMap

ResultMap和返回值为空的的问题

 

要解决的问题:属性名和字段名不一致

代码块如下:

接口:


package com.lx.dao;
import com.lx.pojo.User;
public interface UserMapper {
    User getUserById(int id);
}

穿插:

要想使用@Alias注解的话,必须要在mybatis-config.xml配置typeAlias,例如:


<typeAliases>
     <package name="com.lx.pojo"/>
</typeAliases>

实体类:


package com.lx.pojo;
import org.apache.ibatis.type.Alias;
@Alias("user")
public class User {
    private int id;
    private String name;
    private String pwd;
    public User() {
    }
    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

resouce目录下的数据库配置文件:

在这里插入图片描述


driver=com.Mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
pwd=123456

<?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>
    <properties resource="db.properties" />
<!--    可以给实体类起别名-->
  <typeAliases>
        <package name="com.lx.pojo"/>
    </typeAliases>
   <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="passWord" value="${pwd}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com\lx\dao\UserMapper.xml"/>
    </mappers>
</configuration>

工具类:获取sqlSession


package com.lx.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.IOException;
import java.io.InputStream;
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        //使用Mybatis第一步:获取sqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
    //有了SqlSessionFactory ,可以从中获取SqlSession 的实例
    //SqlSession 在其中包含了面向数据库执行 SQL 命令的所有方法
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

执行sql语句,帮定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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.lx.dao.UserMapper">
  <select id="getUserById" parameterType="int" resultType="user">
      select * from user where id= #{id}
  </select>
</mapper>

测试类:


import com.lx.dao.UserMapper;
import com.lx.pojo.User;
import com.lx.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class test3 {
    @Test
    public void userbyid(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
}

测试结果:

pwd的值为null

mybatis会根据这些查询的列名(会将列名转化为小写,数据库不区分大小写) , 去对应的实体类中查找相应列名的set方法设值 , 由于找不到setPassword() , 所以pwd返回null ; 【自动映射】

在这里插入图片描述

 

解决方法

使用结果集映射:ResultMap

column是数据库表的列名 , property是对应实体类的属性名


<?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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.lx.dao.UserMapper">
<resultMap id="usermap" type="user">
    <!-- id为主键 -->
    <id column="id" property="id"/>
    <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
    <result column="name" property="name"/>
    <result column="password" property="pwd"/>
</resultMap>
    <select id="getUserById" resultMap="usermap">
        select * from user where id=#{id}
    </select>
<!--  <select id="getUserById" parameterType="int" resultType="user">-->
<!--      select * from user where id= #{id}-->
<!--  </select>-->
</mapper>

标签:name,解决方案,resultMap,public,pwd,mybatis,import,id,String
From: https://www.cnblogs.com/dituirenwu/p/17102910.html

相关文章

  • ASP.NET WEB项目大文件上传下载解决方案
    ​ 以ASP.NETCoreWebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API,包括文件的上传和下载。 准备文件上传的API #region 文件上传......
  • JAVA WEB项目大文件上传下载解决方案
    ​ 这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数下面直接贴代码吧,一些难懂的我大部分都加上......
  • 前端报表如何实现无预览打印解决方案或静默打印
    在前端开发中,除了将数据呈现后,我们往往需要为用户提供,打印,导出等能力,导出是为了存档或是二次分析,而打印则因为很多单据需要打印出来作为主要的单据来进行下一环节的票据支撑......
  • 分布式系统02—分布式事务解决方案
    二阶段提交二阶段提交(Two-phaseCommit)是指,在计算机网络以及数据库领域内,为了使基于分布式系统架构下的所有节点在进行事务提交时保持一致性而设计的一种算法(Algorithm)。......
  • spring的@Param注解和mybatis中的@Param注解的区别
    1、spring中@Param(importorg.springframework.data.repository.query.Param;)intselectRoleCount(@Param("businessId")IntegerbusinessId,@Param("memberId")Lo......
  • MyBatis中的#和$有什么区别
    什么是MyBatisMyBatis是一款优秀的持久层框架,特别是在国内(国外据说还是Hibernate的天下)非常的流行,我们常说的SSM组合中的M指的就是#mybatis#。MyBatis支持定制化SQL......
  • 解决mybatis resultMap根据type找不到对应的包问题
    目录mybatisresultMap根据type找不到对应的包mybatisresultMap根据type找不到对应的包这里需要配置typeAliasesPackage自动配置别名typeAliasesPackage定义多个时......
  • Docker容器处于Removal in process 无法删除解决方案
    在正常情况下执行dockerrm会将容器删除,但是如果容器处于Removalinprocess状态下,执行dockerrm会出现:remove/mnt/docker/devicemapper/mnt/remove/mnt/docker/devicema......
  • 关于mybatis resulttype 返回值异常的问题
    目录mybatisresulttype返回值异常例如:resulttype="student"但是当中有些字段为空例如:数据库字段为:s_name实体类字段为namemybatisresultType="map"的常见问题一、......
  • MyBatis-Plus——saveOrUpdate方法如何确定主键
    saveOrUpdate方法:先更新,更新失败返回0;发起查找,查找失败返回0,最后进行插入操作有三种执行情况1.插入的数据不带id插入成功。同时MyBatis-Plus会自动生成一个19位的id,默认主......