亲宝软件园·资讯

展开

Mybatis -resultType resultMap

王老狮 人气:0

Mybatis返回Xml返回值有resultType和resultMap,我们一般都该如何选择呢?

一、resultType

1、resultType介绍

当使用resultType做SQL语句返回结果类型处理时,对于SQL语句查询出的字段在相应的pojo中必须有和它相同的字段对应,而resultType中的内容就是pojo在本项目中的位置。

2、映射规则

3、自动映射注意事项

4、代码演示

1、t_user_test.sql准备

CREATE TABLE `t_user_test` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(60) DEFAULT NULL COMMENT '用户名称',
  `real_name` varchar(60) DEFAULT NULL COMMENT '真实名称',
  `sex` tinyint(3) DEFAULT NULL COMMENT '姓名',
  `mobile` varchar(20) DEFAULT NULL COMMENT '电话',
  `email` varchar(60) DEFAULT NULL COMMENT '邮箱',
  `note` varchar(200) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8;码

2、实体类

package com.enjoylearning.mybatis.entity;

import java.io.Serializable;
import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.mysql.jdbc.Blob;

public class TUser implements Serializable{
	
    private Integer id;

    private String userName;

    private String realName;

    private Byte sex;

    private String mobile;

    private String email;

    private String note;

    private TPosition position;
    
    private List<TJobHistory> jobs ;
    
    private List<HealthReport> healthReports;

    
    private List<TRole> roles;


  
	@Override
	public String toString() {
		String positionId=  (position == null ? "" : String.valueOf(position.getId()));
		return "TUser [id=" + id + ", userName=" + userName + ", realName="
				+ realName + ", sex=" + sex + ", mobile=" + mobile + ", email="
				+ email + ", note=" + note + ", positionId=" + positionId + "]";
	}


	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	
	public Byte getSex() {
		return sex;
	}

	public void setSex(Byte sex) {
		this.sex = sex;
	}


	public String getMobile() {
		return mobile;
	}


	public void setMobile(String mobile) {
		this.mobile = mobile;
	}


	public String getEmail() {
		return email;
	}


	public void setEmail(String email) {
		this.email = email;
	}


	public String getNote() {
		return note;
	}

	public void setNote(String note) {
		this.note = note;
	}


	public TPosition getPosition() {
		return position;
	}


	public void setPosition(TPosition position) {
		this.position = position;
	}

	public List<TJobHistory> getJobs() {
		return jobs;
	}


	public void setJobs(List<TJobHistory> jobs) {
		this.jobs = jobs;
	}

	public List<HealthReport> getHealthReports() {
		return healthReports;
	}

	public void setHealthReports(List<HealthReport> healthReports) {
		this.healthReports = healthReports;
	}

	public List<TRole> getRoles() {
		return roles;
	}

	public void setRoles(List<TRole> roles) {
		this.roles = roles;
	}

}

3、Mapper接口类

public interface TUserTestMapper {
	
	TUser selectByPrimaryKey(Integer id);
	List<TUser> selectAll();

}

4、Mapper 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="com.mybatis.mapper.TUserTestMapper">


	<select id="selectByPrimaryKey" resultType="TUser">
		select
		id, user_name, real_name, sex, mobile, email, note
		from t_user_test
		where id = #{id,jdbcType=INTEGER}
	</select>
	
	
	<select id="selectAll" resultType="TUser">
		select
		id, user_name, real_name, sex, mobile, email, note
		from t_user_test
	</select>


</mapper>

5、配置文件

<?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"/>
	
 	<settings>
		<!-- 设置自动驼峰转换		 -->
		<setting name="mapUnderscoreToCamelCase" value="true" />

		<!-- 开启懒加载 -->		
		 <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。默认:true -->
	  <setting name="aggressiveLazyLoading" value="false" />

	</settings>
	<!-- 别名定义 -->
	<typeAliases>
		<package name="com.enjoylearning.mybatis.entity" />
	</typeAliases>
	
 	<plugins>
		<plugin interceptor="com.enjoylearning.mybatis.Interceptors.ThresholdInterceptor"> 
			<property name="threshold" value="10"/>
		</plugin>
			
  		 <plugin interceptor="com.github.pagehelper.PageInterceptor">
			<property name="pageSizeZero" value="true" />
		</plugin>
	</plugins>


	<!--配置environment环境 -->
	<environments default="development">
		<!-- 环境配置1,每个SqlSessionFactory对应一个环境 -->
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://ip:port/test?useUnicode=true" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>

	<!-- 映射文件,mapper的配置文件 -->
	<mappers>
		<!--直接映射到相应的mapper文件 -->
		<mapper resource="sqlmapper/TUserTestMapper.xml" />
	</mappers>

</configuration>  

6、启动测试类

public class MybatisDemo2 {
	
	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void init() throws IOException {
		//--------------------第一阶段---------------------------
	    // 1.读取mybatis配置文件创SqlSessionFactory
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 1.读取mybatis配置文件创SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		inputStream.close();
	}

	@Test
	//知识点:resultType
	public void testAutoMapping() throws IOException {
		// 2.获取sqlSession	
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 3.获取对应mapper
		TUserTestMapper mapper = sqlSession.getMapper(TUserTestMapper.class);
		// 4.执行查询语句并返回多条数据
		
		List<TUser> users = mapper.selectAll();
		for (TUser tUser : users) {
			System.out.println(tUser);
		}
		
	}
	
}

7、执行结果

sql语句:“com.mysql.jdbc.JDBC4PreparedStatement@654f0d9c: select
		id, user_name, real_name, sex, mobile, email, note
		from t_user_test”执行时间为:35毫秒,已经超过阈值!
TUser [id=1, userName=zhangsan, realName=张三, sex=1, mobile=186995587411, email=zhangsan@qq.com, note=zhangsan的备注, positionId=]
TUser [id=2, userName=lisi, realName=李四, sex=1, mobile=18677885200, email=lisi@qq.com, note=lisi的备注, positionId=]
TUser [id=3, userName=wangwu, realName=王五, sex=2, mobile=18695988747, email=xxoo@163.com, note=wangwu's note, positionId=]

resultType当返基本类型的时候建议选择,当返回POJO类的时候由于需要完全和数据库字段进行对应,存在不灵活、问题排查难等问题。

二、resultMap

1、resultMap  介绍

resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来,在对复杂语句进行联合映射的时候,它很可能可以代替数千行的同等功能的代码。ResultMap 的设计思想是,简单的语句不需要明确的结果映射,而复杂一点的语句只需要描述它们的关系就行了。

2、resultMap属性

  
属性描述
id当前命名空间中的一个唯一标识,用于标识一个result map.
type类的完全限定名, 或者一个类型别名.
autoMapping如果设置这个属性,MyBatis将会为这个ResultMap开启或者关闭自动映射。这个属性会覆盖全局的属性 autoMappingBehavior。默认值为:unset。

3、使用场景

4、resultMap子元素属性

5、代码演示

实体类,配置文件同上

1、mapper接口

public interface TUserMapper {
	List<TUser> selectTestResultMap();
}

2、Mapper.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="com.mybatis.mapper.TUserMapper">

	<resultMap id="UserResultMap" type="TUser" autoMapping="true">
		<id column="id" property="id" />
        <result column="userName" property="userName"/>
		<result column="realName" property="realName" />
		<result column="sex" property="sex" />
		<result column="mobile" property="mobile" />
		<result column="email" property="email" />
		<result column="note" property="note" />
		<association property="position" javaType="TPosition" columnPrefix="post_">
			<id column="id" property="id"/>
			<result column="name" property="postName"/>
			<result column="note" property="note"/>
		</association>
	</resultMap>

	<select  id="selectTestResultMap" resultMap="UserResultMap" >
		select
		    a.id,
		    userName,
			realName,
			sex,
			mobile,
			email,
			a.note,
			b.id  post_id,
			b.post_name,
			b.note post_note
		from t_user a,
			t_position b
		where a.position_id = b.id

	</select>

</mapper>

3、启动测试

public class MybatisDemo2 {
	

	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void init() throws IOException {
		//--------------------第一阶段---------------------------
	    // 1.读取mybatis配置文件创SqlSessionFactory
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 1.读取mybatis配置文件创SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		inputStream.close();
	}


	
	@Test
	public void testResultMap() throws IOException {
		//--------------------第二阶段---------------------------
		// 2.获取sqlSession	
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 3.获取对应mapper
		TUserMapper mapper = sqlSession.getMapper(TUserMapper.class);
		
		//--------------------第三阶段---------------------------

		// 4.执行查询语句并返回单条数据
		List<TUser> users = mapper.selectTestResultMap();
		for (TUser tUser : users) {
			System.out.println(tUser.getUserName());
			System.out.println(tUser.getPosition().getPostName());
		}
	}
}

4、执行结果

sql语句:“com.mysql.jdbc.JDBC4PreparedStatement@19bb07ed: select
            a.id,
            userName,
            realName,
            sex,
            mobile,
            email,
            a.note,
            b.id  post_id,
            b.post_name,
            b.note post_note
        from t_user a,
            t_position b
        where a.position_id = b.id”执行时间为:52毫秒,已经超过阈值!
zhangsan
总经理
lisi
零时工
wangwu
总经理

三、结论

当返回对象为基础类型时建议走resultType,当返回对象为POJO时,强制走resultMap。同时可以参考阿里巴巴JAVA开发手册中的5.4.3节,返回要解耦,不讷讷更直接使用resultClass。

加载全部内容

相关教程
猜你喜欢
用户评论