MyBatis数据库连接的基本使用-补充

补充1  MyBatis使用过程中,返回值类型可能是Map,不一定是实体类

返回查询结果也可以是一个Map,不一定是实体类 

(1)mybatis会先将查询结果返回为一个map,字段名作为key,字段值作为value,保存在map中,后面再转化为实体类

(2)如果不写实体类,就返回一个Map,想得到其中的字段值,需要调用map.get()方法来获取值,缺点就是需要先知道字段名 

EmpMapper.xml中配置:

<!-- 返回map类型的结果 -->
  <!-- 也可以将返回结果简写成map,map即为java.util.Map -->
  <select id="findOne" parameterType="int" resultType="java.util.Map">
    SELECT * FROM T_TABLE WHERE ID=#{id}
  </select>

测试代码:

    /**
     * 查询结果为map类型,不返回实体类,返回java.util.Map
     */
    @Test
    public void test4() {
        Map map=session.selectOne("clyang.findOne", 4);
        System.out.println(map);
        //oracle数据库会将字段名自动变成大写,如果要取值需要写成大写
        System.out.println(map.get("NAME"));//使用Map的get方法得到属性值
        session.close();    
    }

测试结果:

 补充2 解决数据库字段名和实体类属性名不一致

(1)使用别名,将查询后的字段名改别名,别名跟实体类的名字一样

(2)使用resultMap解决

新的实体类,属性名跟表的字段名都不一样:

public class NewEmployee {
  private int empID;
  private String empName;
  private int empAge;
  
public int getEmpID() {
    return empID;
}
public void setEmpID(int empID) {
    this.empID = empID;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}
public int getEmpAge() {
    return empAge;
}
public void setEmpAge(int empAge) {
    this.empAge = empAge;
}
@Override
public String toString() {
    return "NewEmployee [empID=" + empID + ", empName=" + empName + ", empAge=" + empAge + "]";
}

EmpMapper.xml中配置,resultType需改成resultMap,并配置resultMap,告诉返回的字段值如何一一对应到新的实体类:

<!-- 使用resultMap解决表的字段名和实体类的属性名不一致的情况 -->
  <resultMap id="resultMapID" type="entity.NewEmployee">
    <result property="empID" column="id" />
    <result property="empName" column="name" />
    <result property="empAge" column="age" />
  </resultMap>
  
  <select id="findOneByNewEmp" parameterType="int" resultMap="resultMapID">
  SELECT * FROM T_TABLE WHERE ID=#{id}
  </select>

测试代码:

    /**
     * 当数据表的字段名和实体类不一致时,查询的返回结果为null
     * 可以修改返回结果的别名,让别名和实体类的属性名一致,或者配置文件中配置resultMap,即可解决
     */
    @Test
    public void test5() {
        NewEmployee emp=new NewEmployee();
        emp=session.selectOne("clyang.findOneByNewEmp", 4);
        System.out.println(emp);
        session.close();
    }

测试结果:

原文地址:https://www.cnblogs.com/youngchaolin/p/10353724.html