1、概念
resultMap屬于mybatis返回操作結果的一個標簽,可以用來映射select查詢出來結果的集合,主要作用是將實體類中的字段與數據庫表中的字段進行關聯映射。并且支持復雜的返回結果類型。
2、使用場景
2.1 屬性映射
當數據庫字段和項目中的實體屬性不一致時,可以使resultMap進行數據庫字段和實體類屬性的映射關系
比如:
column="id" jdbcType="integer" property="id" /> column="user_name" jdbcType="VARCHAR" property="userName" />
說明:如果數據庫字段和實體類屬性一致的情況下,可以省略不寫。
2.2 實現Java復雜實體類用法
a.初始化腳本
DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) CHARACTER SET armscii8 DEFAULT NULL, `password` varchar(255) CHARACTER SET armscii8 DEFAULT NULL, `last_login_time` datetime DEFAULT NULL, `sex` tinyint(4) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;-- ------------------------------ Records of t_user-- ----------------------------INSERT INTO `t_user` VALUES ('1', 'xiaoxin', '123', '2019-07-27 16:01:21', '1');INSERT INTO `t_user` VALUES ('2', 'jack jo', '123', '2019-07-24 16:01:37', '1');INSERT INTO `t_user` VALUES ('4', 'landengdeng', '123', '2019-07-24 16:01:37', '1');INSERT INTO `t_user` VALUES ('5', 'max', '123', '2019-07-24 16:01:37', '1');INSERT INTO `t_user` VALUES ('6', 'liua11', '123456', null, '1');INSERT INTO `t_user` VALUES ('7', 'xiaozhang', '888888', null, '1');DROP TABLE IF EXISTS `t_hobby`;CREATE TABLE `t_hobby` ( `id` int(11) NOT NULL, `hobbyName` varchar(50) CHARACTER SET utf8 DEFAULT NULL, `userId` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------ Records of t_hobby-- ----------------------------INSERT INTO `t_hobby` VALUES ('0', '音樂', '2');INSERT INTO `t_hobby` VALUES ('1', '籃球', '1');INSERT INTO `t_hobby` VALUES ('2', '讀書', '1');
b.定義實體類
定義實體 UserDO.java
public class UserDO {private Integer id;private String userName;private String password;private Integer sex;private Date lastLoginTime;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 getPassword() {return password; }public void setPassword(String password) {this.password = password; }public Integer getSex() {return sex; }public void setSex(Integer sex) {this.sex = sex; }public Date getLastLoginTime() {return lastLoginTime; }public void setLastLoginTime(Date lastLoginTime) {this.lastLoginTime = lastLoginTime; }@Override public String toString() {return "UserDO{" +"id=" + id +", userName='" + userName + '\'' +", password='" + password + '\'' +", sex=" + sex +", lastLoginTime=" + lastLoginTime +'}'; }
定義實體類 HobbyDO.java
public class HobbyDO {private Integer id;private String hobbyName;private Integer userId;public Integer getId() {return id; }public void setId(Integer id) {this.id = id; }public String getHobbyName() {return hobbyName; }public void setHobbyName(String hobbyName) {this.hobbyName = hobbyName; }public Integer getUserId() {return userId; }public void setUserId(Integer userId) {this.userId = userId; }@Override public String toString() {return "HobbyDO{" +"id=" + id +", hobbyName='" + hobbyName + '\'' +", userId=" + userId +'}'; }
c.定義model類
定義類 HobbyVO.java? 用來演示一對一
public class HobbyVo extends HobbyDO {private UserDO user ;public UserDO getUser() {return user; }public void setUser(UserDO user) {this.user = user; }}定義類 UserVO.java 用來演示1對多public class UserVO extends UserDO {private Listlist;public ListgetList() {return list; }public void setList(Listlist) {this.list = list; }}
d.定義mapper類文件
定義UserInfoMapper.java文件
package my.springboot.mybatis.dao;import java.util.List;import java.util.Map;import my.springboot.mybatis.entity.HobbyDO;import my.springboot.mybatis.entity.UserDO;import my.springboot.mybatis.model.UserVO;import org.apache.ibatis.annotations.Mapper;@Mapperpublic interface UserInfoMapper { UserDO get(Integer id); List getUserVOMap(Integer id); List getHobbyByUserId(Integer userId);}
定義HobbyMapper.java文件
package my.springboot.mybatis.dao;import my.springboot.mybatis.entity.HobbyDO;import my.springboot.mybatis.entity.UserDO;import my.springboot.mybatis.model.HobbyVo;import org.apache.ibatis.annotations.Mapper;import java.util.List;import java.util.Map;@Mapperpublic interface HobbyMapper { List getHobbyByUserId(Integer userId); List getHobbyVOMap();}
e.定義service服務
定義IUserInfoService.java
package my.springboot.mybatis.service;import my.springboot.mybatis.entity.UserDO;import my.springboot.mybatis.model.HobbyVo;import my.springboot.mybatis.model.UserVO;import java.util.List;public interface IUserInfoService { List getUserVOMap(Integer userId); List getHobbyMap();}
定義UserInfoService.java
package my.springboot.mybatis.service.impl;import my.springboot.mybatis.dao.HobbyMapper;import my.springboot.mybatis.dao.UserInfoMapper;import my.springboot.mybatis.entity.UserDO;import my.springboot.mybatis.model.HobbyVo;import my.springboot.mybatis.model.UserVO;import my.springboot.mybatis.service.IUserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class UserInfoService implements IUserInfoService {@Autowired private UserInfoMapper mapper;@Autowired private HobbyMapper hobbyMapper;@Override public List getUserVOMap(Integer id) {return this.mapper.getUserVOMap(id); }@Override public ListgetHobbyMap() {return hobbyMapper.getHobbyVOMap(); }}
f.定義測試控制器
HomeController.java
package my.springboot.mybatis.controller;import my.springboot.mybatis.entity.UserDO;import my.springboot.mybatis.model.HobbyVo;import my.springboot.mybatis.model.UserVO;import my.springboot.mybatis.service.IUserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import javax.jws.soap.SOAPBinding;import java.util.Date;import java.util.List;@Controllerpublic class HomeController {@Autowired private IUserInfoService userInfoService;@RequestMapping("index") //注解映射請求路徑 @ResponseBody //可以將java對象轉為json格式的數據 public String index() { List vo=userInfoService.getUserVOMap(1); List list=userInfoService.getHobbyMap(); return "Hello World !"; }}
g.定義xml文件
定義HobbyMapper.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="my.springboot.mybatis.dao.HobbyMapper"><select id="getHobbyByUserId" resultType="my.springboot.mybatis.entity.HobbyDO" parameterType="integer"> select * from t_hobby where userId= #{id}</select><resultMap id="hobbyVOMap" type="my.springboot.mybatis.model.HobbyVo"><id property="id" column="id"/><association property="user" column="userId" javaType="my.springboot.mybatis.entity.HobbyDO" select="my.springboot.mybatis.dao.UserInfoMapper.get"></association></resultMap><select id="getHobbyVOMap" resultMap="hobbyVOMap" parameterType="integer"> select * from t_hobby</select></mapper>
定義UserInfoMapper.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="my.springboot.mybatis.dao.UserInfoMapper"><select id="get" resultType="my.springboot.mybatis.entity.UserDO"> select `id`,`user_name`,`password`,`last_login_time`,`sex` from t_user where id = #{value}</select><!--跨xml文件寫法 my.springboot.mybatis.dao.HobbyMapper.getHobbyByUserId--> <resultMap id="userVOMap" type="my.springboot.mybatis.model.UserVO"><id property="id" column="id"/><collection property="list" column="id" ofType="my.springboot.mybatis.entity.HobbyDO" select="my.springboot.mybatis.dao.HobbyMapper.getHobbyByUserId"></collection></resultMap><select id="getUserVOMap" resultMap="userVOMap" parameterType="integer"> select * from t_user</select><select id="getHobbyByUserId" resultType="my.springboot.mybatis.entity.HobbyDO" parameterType="integer"> select * from t_hobby where userId= #{id}</select>
</mapper>
訪問地址:http://localhost:8090/index
項目結構:
3、總結
resultMap用途主要有一下兩點:
1、數據庫字段和Java類屬性映射
2、實現復雜的model類的查詢
model中包含實體類使用關鍵字:association
<select id="getHobbyByUserId" resultType="my.springboot.mybatis.entity.HobbyDO" parameterType="integer">select * from t_hobby where userId= #{id}
</select>
<resultMap id="hobbyVOMap" type="my.springboot.mybatis.model.HobbyVo">
<id property="id" column="id"/>
<association property="user" column="userId" javaType="my.springboot.mybatis.entity.HobbyDO"select="my.springboot.mybatis.dao.UserInfoMapper.get">
<!-- 說明:如果調用的方法不在當前xml里面,需要指明完整的mapper路徑 my.springboot.mybatis.dao.UserInfoMapper.get --> </association>
</resultMap>
<select id="getHobbyVOMap" resultMap="hobbyVOMap" parameterType="integer">select * from t_hobby
</select>
model中包含集合使用:collection 關鍵代碼
<resultMap id="userVOMap" type="my.springboot.mybatis.model.UserVO">
<id property="id" column="id"/>
<collection property="list" column="id" ofType="my.springboot.mybatis.entity.HobbyDO" select="my.springboot.mybatis.dao.HobbyMapper.getHobbyByUserId">
</collection>
</resultMap>
<select id="getUserVOMap" resultMap="userVOMap" parameterType="integer">select * from t_user
</select>
<select id="getHobbyByUserId" resultType="my.springboot.mybatis.entity.HobbyDO" parameterType="integer">select * from t_hobby where userId= #{id}
</select>
注意:實際的查詢過程當中,并不是必須要保證數據庫字段名稱和實體的屬性名稱保持一致,如果查詢語句查詢字段指定別名,也是可以正常做映射的,要會靈活使用。
IT技術分享社區
個人博客網站:https://programmerblog.xyz
文章推薦程序員效率:畫流程圖常用的工具程序員效率:整理常用的在線筆記軟件遠程辦公:常用的遠程協助軟件,你都知道嗎?51單片機程序下載、ISP及串口基礎知識硬件:斷路器、接觸器、繼電器基礎知識