1.大家学习MyBatis时,可能会碰到实体类属性跟数据库字段不同的情况

如:数据库    ------  实体类

stuname  ---->  name

即: 数据库中的stuname字段对应的事实体类里的name属性

如果这时,我们要用常规的查询方法时是不能正确查询到stuname的值的,它会显示为null

这时,我们可以使用我们的resultMap来解决这一问题。。。

源码介绍与对比:

1.Student.java (实体类)

package cn.zhang.entity;

import java.util.Date;

/**
* 学生实体类
*
*/
public class Student { private Integer stuno;
private String name;
private Integer stuage;
private Date studate; @Override
public String toString() {
return "Student [stuno=" + stuno + ", name=" + name + ", stuage="
+ stuage + ", studate=" + studate + "]";
} public Integer getStuno() {
return stuno;
} public void setStuno(Integer stuno) {
this.stuno = stuno;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getStuage() {
return stuage;
} public void setStuage(Integer stuage) {
this.stuage = stuage;
} public Date getStudate() {
return studate;
} public void setStudate(Date studate) {
this.studate = studate;
} }

2.mybatis-config.xml (MyBatis的配置文件)

<?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>
<!-- 配置别名 -->
<typeAliases>
<!--方式一: 按类型名定制别名 -->
<typeAlias type="cn.zhang.entity.Student" alias="Student" />
<!--方式二: 拿当前指定包下的简单类名作为别名 -->
<!-- <package name="cn.zhang.entity"/> -->
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<!-- 使用jdbc的事务 -->
<transactionManager type="JDBC" />
<!-- 使用自带的连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/y2161" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/zhang/dao/StudentDAO.xml" />
</mappers>
</configuration>

3.MybatisUtil.java (获得session的工具类)

package cn.zhang.util;

import java.io.IOException;
import java.io.Reader; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; /**
* 获得session的工具类
*
*/
public class MybatisUtil { private static String config = "mybatis-config.xml";
static Reader reader;
static {
try {
reader = Resources.getResourceAsReader(config);
} catch (IOException e) {
e.printStackTrace();
}
}
private static SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(reader); // 提供一个可以获取到session的方法
public static SqlSession getSession() throws IOException { SqlSession session = factory.openSession();
return session;
}
}

4.StudentDao.java (定义方法的接口)

package cn.zhang.dao;

import java.io.IOException;
import java.util.List; import cn.zhang.entity.Student; public interface StudentDao { /**
* 查询所有记录
* @return
* @throws IOException
*/
public List<Student> findAll() throws IOException; }

5.StudentDaoImpl.java (实现接口方法的实现类)

package cn.zhang.dao.impl;

import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import cn.zhang.dao.StudentDao;
import cn.zhang.entity.Student;
import cn.zhang.util.MybatisUtil; public class StudentDaoImpl implements StudentDao {
SqlSession session; public StudentDaoImpl() throws IOException {
session = MybatisUtil.getSession();
} /**
* 查询所有
*/
public java.util.List<Student> findAll() throws IOException {
List<Student> list = session.selectList("findAll");
session.close();
return list;
} }

6.StudentDAO.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="cn.zhang.dao"> <!-- 查询所有 -->
<select id="findAll" resultType="Student">
select * from student
</select> </mapper>

用resultMap的配法:

<?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="cn.zhang.dao"> <!-- 结果映射,指定了数据库和实体类中的对应值 -->
<resultMap type="Student" id="findstudent">
<result property="name" column="stuname" />
</resultMap> <!-- 查询所有 -->
<select id="findAll" resultMap="findstudent">
select * from student
</select> </mapper>

7.log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=debug, stdout

8..MyTest.java (测试类)

package cn.zhang.test;

import java.io.IOException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import cn.zhang.dao.StudentDao;
import cn.zhang.dao.impl.StudentDaoImpl;
import cn.zhang.entity.Student; public class MyTest { StudentDao dao;
@Before
public void initData() throws IOException{
dao=new StudentDaoImpl();
} /**
* 查询所有学生
* @throws IOException
*/
@Test
public void findAll() throws IOException{
List<Student> list = dao.findAll();
for (Student student : list) {
System.out.println("编号: "+student.getStuno()+"姓名:"+student.getName());
} } }

对应StudentDAO.xml中常规配法的结果:

对应StudentDAO.xml中resultMap配法的结果:

这样就可以成功的拿到值了,这就是resultMap的作用。

是不是很简单,这里只是记录一下。。

MyBatis的resultMap的更多相关文章

  1. Mybatis的ResultMap的使用

    本篇文章通过一个实际工作中遇到的例子开始吧: 工程使用Spring+Mybatis+Mysql开发.具体的业务逻辑很重,对象之间一层一层的嵌套.和数据库表对应的是大量的model类,而和前端交互的是V ...

  2. 使用MyBatis的resultMap高级查询时常用的方式总结

    以下内容已经通过楼主测试, 从pd设计数据库到测试完成, 之前楼主也没有过Mybatis 使用resultMap觉得有点乱,最近抽出时间总结了一下也算对MyBatis的resultMap进行一次系统的 ...

  3. Mybatis的ResultMap的使用(转)

    本篇文章通过一个实际工作中遇到的例子开始吧: 工程使用Spring+Mybatis+Mysql开发.具体的业务逻辑很重,对象之间一层一层的嵌套.和数据库表对应的是大量的model类,而和前端交互的是V ...

  4. 【MyBatis】ResultMap

    [MyBatis]ResultMap 转载:https://www.cnblogs.com/yangchongxing/p/10486854.html 支持的 JDBC 类型为了未来的参考,MyBat ...

  5. 使用mybatis的resultMap进行复杂查询

        记录下mybatis的集合查询中碰到的问题 https://jaychang.iteye.com/blog/2357143   MyBatis ofType和javaType区别 https: ...

  6. mybatis 使用resultMap实现关联数据的查询(association 和collection )

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "- ...

  7. mybatis 使用resultMap实现数据库的操作

    resultType:直接表示返回类型 resultMap:对外部resultMap的引用 二者不能同时使用 创建一个实体类Role和User public class Role { private ...

  8. Mybatis之ResultMap一个简短的引论,关联对象

    基础部分能够查看我的还有一篇博客http://blog.csdn.net/elim168/article/details/40622491 MyBatis中在查询进行select映射的时候.返回类型能 ...

  9. SSM框架开发web项目系列(三) MyBatis之resultMap及关联映射

    前言 在上篇MyBatis基础篇中我们独立使用MyBatis构建了一个简单的数据库访问程序,可以实现单表的基本增删改查等操作,通过该实例我们可以初步了解MyBatis操作数据库需要的一些组成部分(配置 ...

随机推荐

  1. IoC在ASP.NET Web API中的应用

    控制反转(Inversion of Control,IoC),简单地说,就是应用本身不负责依赖对象的创建和维护,而交给一个外部容器来负责.这样控制权就由应用转移到了外部IoC容器,控制权就实现了所谓的 ...

  2. Node.js Base64 Encoding和Decoding

    如何在Node.js中encode一个字符串呢?是否也像在PHP中使用base64_encode()一样简单? 在Node.js中有许多encoding字符串的方法,而不用像在JavaScript中那 ...

  3. C# 的 Dictionary 寫入前應注意事項

    一個已上線.用戶龐大的系統,幾個月來第一次出現這個系統錯誤訊息 : 「已經加入含有相同索引鍵的項目」「已添加了具有相同键的项」An item with the same key has already ...

  4. YY一下淘宝商品模型

    淘宝的电商产品种类非常丰富,必然得力于其商品模型的高度通用性和扩展性. 下面我将亲自操作淘宝商品的发布过程,结合网上其他博客对淘宝网商品库的分析,简单谈谈我的理解. 注:下面不特殊说明,各个表除主键外 ...

  5. LINQ系列:LINQ to XML操作

    LINQ to XML操作XML文件的方法,如创建XML文件.添加新的元素到XML文件中.修改XML文件中的元素.删除XML文件中的元素等. 1. 创建XML文件 string xmlFilePath ...

  6. Android之JSON解析

    做个Android网络编程的同学一定对于JSON解析一点都不陌生,因为现在我们通过手机向服务器请求资源,服务器给我们返回的数据资源一般都是以JSON格式返回,当然还有一些通过XML格式返回,相对JSO ...

  7. Easyui datagrid 显示隐藏列

    html:         <div style="float: left; width: 1450px; height:auto;  ">             & ...

  8. OracleDBA之用户管理

    再分享一下Oracle中对用户的管理,以下这些东西是我的麦库上存的当时学Oracle的学习笔记今天拿出来和大家分享一下,转载请注明出处,下面用的Oracle的版本是10g,用的时WinServer20 ...

  9. 如何用Perl对Excel的数据进行提取并分析

    巡检类工作经常会出具日报,最近在原有日报的基础上又新增了一个表的数据量统计日报,主要是针对数据库中使用较频繁,数据量又较大的31张表.该日报有两个sheet组成,第一个sheet是数据填写,第二个sh ...

  10. php这是一个随机打印输出字符串的例子

    <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); define(& ...