mybatis和数据库字段不匹配,使用hashmap传递数据

1、mybatis和数据库字段不匹配

如果我们数据库的字段名字和实体类的属性名字不一直,就徐璈通过resultmap来进行配置,保证数据能正确回到我们的实体类的那个中:

<!-- type:实体类路径
      id  唯一标记
     -->
    <resultMap type="com.xingxue.entity.TypeBean" id="typeMap">
        <!-- 
            columu: 表的字段名
            property: 类的属性名
            javaType: java的数据类型
            jdbcType: 数据库的数据类型
         -->
        <result jdbcType="VARCHAR" javaType="java.lang.String" column="name" property="tname"/>
        <result column="id" property="id"/>
        <result column="statu" property="statu"/>
        <result column="createdate" javaType="java.util.Date" jdbcType="date" property="createdate"/>
    </resultMap>

    <select id="selectType1" resultMap="typeMap">
        select * from type where id = 1
    </select>

2、使用hashmap来进行数据传输

如果我们使用了hashmap,就省掉了编写实体类和resutMap的一些操作,返回值直接是hashmap,参数直接是hashmap,代码如下:

<?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.xingxue.dao.GoodsMapper">

    <select id="selectGoodsById" parameterType="java.util.HashMap"  resultType="java.util.HashMap">

        select * from goods where id = #{id}

    </select>

</mapper>   

java代码:

package com.xingxue.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

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 com.xingxue.entity.TypeBean;

public class MyBatisUtils2 {

    public static void main(String[] args) throws IOException {

        //获取会话工厂
        InputStream is = Resources.getResourceAsStream("com/config/mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); 

        //获取会话
        SqlSession session = factory.openSession();

        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("id", 24);

        HashMap<String, Object> result = session.selectOne("com.xingxue.dao.GoodsMapper.selectGoodsById", param);

        System.out.println("===" + result);

    }

}

这样就会得一个封装在hashmap里面的实体数据,此处注意,如果我们数据库的字段是空,他hashmap会选择不封装这个字段。

猜你喜欢

转载自blog.csdn.net/sky274548769/article/details/81330792