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>

测试结果:
在这里插入图片描述
good good study ! day day up !

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatisResultMap用于解决数据库字段与实体类属性不一致的情况。通过建立一种映射关系,使表的字段与实体类的属性一一对应。 在mapper.xml文件,可以通过ResultMap属性来指定映射。首先,需要在mapper.xml文件定义一个ResultMap,指定映射的JavaBean类型,并为该ResultMap指定一个唯一的id。在ResultMap,使用<result>标签来指定字段和属性的映射关系。其,column属性指代表数据库的字段,property属性指代JavaBean的属性名。例如: ``` <resultMap id="brandResultMap" type="brand"> <result column="brand_name" property="brandName"/> <result column="company_name" property="companyName"/> </resultMap> ``` 接着,在sql语句使用<select>标签,通过resultMap属性指定使用哪个ResultMap进行映射。例如: ``` <select id="selectAll" resultMap="brandResultMap"> select * from tb_brand; </select> ``` 如果需要返回的对象类包含对象属性,同样需要进行映射。在ResultMap,可以使用<association>标签来指定对象属性的映射关系。例如: ``` <resultMap type="com.pjf.mybatis.po.Hotel" id="myHotel"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="hotel_name" property="hotelName" jdbcType="VARCHAR" /> <result column="hotel_address" property="hotelAddress" jdbcType="VARCHAR" /> <result column="price" property="price" jdbcType="INTEGER" /> <!-- 这里可以继续添加其他属性的映射 --> </resultMap> ``` 然后,在sql语句使用<select>标签,通过resultMap属性指定使用哪个ResultMap进行映射。例如: ``` <select id="getHotel" resultMap="myHotel"> select * from hotel where id=#{id} </select> ``` 通过使用ResultMap,我们可以灵活地处理实体类与数据库表字段之间的映射关系,以及实体类对象属性的映射。这样可以更好地组织和管理数据对象的映射规则,提高代码的可读性和可维护性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [mybatis关于resultMap的使用](https://blog.csdn.net/a18372016358/article/details/129375251)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [MyBatis学习(3)—— resultMap的使用](https://blog.csdn.net/weixin_41565013/article/details/88920898)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值