Mybatis 开发要点 -resultType 和 resultMap 的区别?
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" />
<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>
<environments default="development">
<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>
<mappers>
<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 属性
<table border="1" cellspacing="0"><tbody><tr><td><p><strong>属性</strong></p></td><td><p><strong>描述</strong></p></td></tr><tr><td><p>id</p></td><td><p>当前命名空间中的一个唯一标识,用于标识一个 result map.</p></td></tr><tr><td><p>type</p></td><td><p>类的完全限定名, 或者一个类型别名.</p></td></tr><tr><td><p>autoMapping</p></td><td><p>如果设置这个属性,MyBatis 将会为这个 ResultMap 开启或者关闭自动映射。这个属性会覆盖全局的属性 autoMappingBehavior。默认值为:unset。</p></td></tr></tbody></table>
3、使用场景
字段有自定义的转化规则
复杂的多表查询
4、resultMap 子元素属性
id –一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能,一对多的查询中用于结果集合并;
result – 注入到字段或 JavaBean 属性的普通结果
association – 一个复杂类型的关联;许多结果将包装成这种类型。关联可以指定为一个 resultMap 元素,或者引用一个
collection – 一个复杂类型的集合
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="mob
ile" />
<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());
}
}
}
评论