经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
MyBatis?多表联合查询及优化方法
来源:jb51  时间:2022/8/2 12:45:18  对本文有异议

这篇文章我打算来简单的谈谈 mybatis 的多表联合查询。起初是觉得挺简单的,没必要拿出来写,毕竟 mybatis 这东西现在是个开发的都会用,而且网上的文章也是一搜罗一大堆,根本就用不着我来重复。但是吧,就我前几天在做一个多表联合查询的时候,竟然出了很多意想不到的问题,而且这些问题的出现,并不是对 mybatis 不了解,而是在用的过程中会或多或少的忽略一些东西,导致提示各种错误。

背景

老规矩,开始之前,还是要先说说这件事的背景。也就是最近几天,公司要做一个后台的管理平台,由于之前的一些限制,这次要做成单独的项目进行部署,因此就要重新考虑很多东西。索性这几天有时间,就做了一个小 Demo ,实现 mybatis 的多表联合查询的,由于之前用的是 Hibernate 做的联合查询,众所周知,Hibernate 是全自动的数据库持久层框架,它可以通过实体来映射数据库,通过设置一对多、多对一、一对一、多对多的关联来实现联合查询。

正文

下面就来说一下 mybatis 是通过什么来实现多表联合查询的。首先看一下表关系,如图:

这里,我已经搭好了开发的环境,用到的是 SpringMVC + Spring + MyBatis,当然,为了简单期间,你可以不用搭前端的框架,只使用 Spring + MyBatis 就可以,外加 junit 测试即可。环境我就不带大家搭了,这里只说涉及到联合查询的操作。
设计好表之后,我用到了 mybatis 的自动生成工具 mybatis generator 生成的实体类、mapper 接口、以及 mapper xml 文件。由于是测试多表联合查询,因此需要自己稍加改动。
下面是 User 和 Role 的实体类代码:

User

  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.domain;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. public class User implements Serializable {
  5. private String id;
  6. private String username;
  7. private String password;
  8. private List<Role> roles;
  9. private static final long serialVersionUID = 1L;
  10. public String getId() {
  11. return id;
  12. }
  13. public void setId(String id) {
  14. this.id = id == null ? null : id.trim();
  15. }
  16. public String getUsername() {
  17. return username;
  18. }
  19. public void setUsername(String username) {
  20. this.username = username == null ? null : username.trim();
  21. }
  22. public String getPassword() {
  23. return password;
  24. }
  25. public void setPassword(String password) {
  26. this.password = password == null ? null : password.trim();
  27. }
  28. public List<Role> getRoles() {
  29. return roles;
  30. }
  31. public void setRoles(List<Role> roles) {
  32. this.roles = roles;
  33. }
  34. @Override
  35. public boolean equals(Object that) {
  36. if (this == that) {
  37. return true;
  38. }
  39. if (that == null) {
  40. return false;
  41. }
  42. if (getClass() != that.getClass()) {
  43. return false;
  44. }
  45. User other = (User) that;
  46. return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
  47. && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
  48. && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()));
  49. }
  50. @Override
  51. public int hashCode() {
  52. final int prime = 31;
  53. int result = 1;
  54. result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
  55. result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
  56. result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode());
  57. return result;
  58. }
  59. }</span>

Role

  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.domain;
  2. import java.io.Serializable;
  3. public class Role implements Serializable {
  4. private String id;
  5. private String name;
  6. private String jsms;
  7. private String bz;
  8. private Integer jlzt;
  9. private String glbm;
  10. private String userid;
  11. private static final long serialVersionUID = 1L;
  12. public String getId() {
  13. return id;
  14. }
  15. public void setId(String id) {
  16. this.id = id == null ? null : id.trim();
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name == null ? null : name.trim();
  23. }
  24. public String getJsms() {
  25. return jsms;
  26. }
  27. public void setJsms(String jsms) {
  28. this.jsms = jsms == null ? null : jsms.trim();
  29. }
  30. public String getBz() {
  31. return bz;
  32. }
  33. public void setBz(String bz) {
  34. this.bz = bz == null ? null : bz.trim();
  35. }
  36. public Integer getJlzt() {
  37. return jlzt;
  38. }
  39. public void setJlzt(Integer jlzt) {
  40. this.jlzt = jlzt;
  41. }
  42. public String getGlbm() {
  43. return glbm;
  44. }
  45. public void setGlbm(String glbm) {
  46. this.glbm = glbm == null ? null : glbm.trim();
  47. }
  48. public String getUserid() {
  49. return userid;
  50. }
  51. public void setUserid(String userid) {
  52. this.userid = userid == null ? null : userid.trim();
  53. }
  54. @Override
  55. public boolean equals(Object that) {
  56. if (this == that) {
  57. return true;
  58. }
  59. if (that == null) {
  60. return false;
  61. }
  62. if (getClass() != that.getClass()) {
  63. return false;
  64. }
  65. Role other = (Role) that;
  66. return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
  67. && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
  68. && (this.getJsms() == null ? other.getJsms() == null : this.getJsms().equals(other.getJsms()))
  69. && (this.getBz() == null ? other.getBz() == null : this.getBz().equals(other.getBz()))
  70. && (this.getJlzt() == null ? other.getJlzt() == null : this.getJlzt().equals(other.getJlzt()))
  71. && (this.getGlbm() == null ? other.getGlbm() == null : this.getGlbm().equals(other.getGlbm()))
  72. && (this.getUserid() == null ? other.getUserid() == null : this.getUserid().equals(other.getUserid()));
  73. }
  74. @Override
  75. public int hashCode() {
  76. final int prime = 31;
  77. int result = 1;
  78. result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
  79. result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
  80. result = prime * result + ((getJsms() == null) ? 0 : getJsms().hashCode());
  81. result = prime * result + ((getBz() == null) ? 0 : getBz().hashCode());
  82. result = prime * result + ((getJlzt() == null) ? 0 : getJlzt().hashCode());
  83. result = prime * result + ((getGlbm() == null) ? 0 : getGlbm().hashCode());
  84. result = prime * result + ((getUserid() == null) ? 0 : getUserid().hashCode());
  85. return result;
  86. }
  87. }</span>

首先讲一下业务,这里用到的 User 、Role 的对应关系是,一个用户有多个角色,也就是 User : Role 是 1 : n 的关系。因此,在 User 的实体中加入一个 Role 的属性,对应一对多的关系。
然后就是 mapper 接口和 xml 文件了:
mapper接口
UserMapper

  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.mapper;
  2. import com.sica.domain.User;
  3. import java.util.List;
  4. public interface UserMapper {
  5. int deleteByPrimaryKey(String id);
  6. int insert(User record);
  7. int insertSelective(User record);
  8. User selectByPrimaryKey(String id);
  9. int updateByPrimaryKeySelective(User record);
  10. int updateByPrimaryKey(User record);
  11. List<User> queryForList();
  12. }</span>

mapper xml文件
UserMapper

  1. <span style="font-family:Comic Sans MS;font-size:12px;"><?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="com.sica.mapper.UserMapper">
  4. <resultMap id="BaseResultMap" type="com.sica.domain.User">
  5. <id column="id" property="id" jdbcType="VARCHAR"/>
  6. <result column="username" property="username" jdbcType="VARCHAR"/>
  7. <result column="password" property="password" jdbcType="VARCHAR"/>
  8. </resultMap>
  9. <resultMap id="queryForListMap" type="com.sica.domain.User">
  10. <id column="id" property="id" jdbcType="VARCHAR"/>
  11. <result column="username" property="username" jdbcType="VARCHAR"/>
  12. <result column="password" property="password" jdbcType="VARCHAR"/>
  13. <collection property="roles" javaType="java.util.List" ofType="com.sica.domain.Role">
  14. <id column="r_id" property="id" jdbcType="VARCHAR" />
  15. <result column="r_name" property="name" jdbcType="VARCHAR" />
  16. <result column="r_jsms" property="jsms" jdbcType="VARCHAR" />
  17. <result column="r_bz" property="bz" jdbcType="VARCHAR" />
  18. <result column="r_jlzt" property="jlzt" jdbcType="INTEGER" />
  19. <result column="r_glbm" property="glbm" jdbcType="VARCHAR" />
  20. </collection>
  21. </resultMap>
  22. <select id="queryForList" resultMap="queryForListMap">
  23. SELECT
  24. u.id,
  25. u.username,
  26. u.password,
  27. r.id r_id,
  28. r.name r_name,
  29. r.jsms r_jsms,
  30. r.bz r_bz,
  31. r.jlzt r_jlzt,
  32. r.glbm r_glbm
  33. FROM
  34. user u
  35. LEFT JOIN
  36. role r
  37. ON
  38. u.id = r.userid
  39. </select>
  40. <sql id="Base_Column_List">
  41. id, username, password
  42. </sql>
  43. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String">
  44. select
  45. <include refid="Base_Column_List"/>
  46. from user
  47. where id = #{id,jdbcType=VARCHAR}
  48. </select>
  49. <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
  50. delete from user
  51. where id = #{id,jdbcType=VARCHAR}
  52. </delete>
  53. <insert id="insert" parameterType="com.sica.domain.User">
  54. insert into user (id, username, password
  55. )
  56. values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
  57. )
  58. </insert>
  59. <insert id="insertSelective" parameterType="com.sica.domain.User">
  60. insert into user
  61. <trim prefix="(" suffix=")" suffixOverrides=",">
  62. <if test="id != null">
  63. id,
  64. </if>
  65. <if test="username != null">
  66. username,
  67. </if>
  68. <if test="password != null">
  69. password,
  70. </if>
  71. </trim>
  72. <trim prefix="values (" suffix=")" suffixOverrides=",">
  73. <if test="id != null">
  74. #{id,jdbcType=VARCHAR},
  75. </if>
  76. <if test="username != null">
  77. #{username,jdbcType=VARCHAR},
  78. </if>
  79. <if test="password != null">
  80. #{password,jdbcType=VARCHAR},
  81. </if>
  82. </trim>
  83. </insert>
  84. <update id="updateByPrimaryKeySelective" parameterType="com.sica.domain.User">
  85. update user
  86. <set>
  87. <if test="username != null">
  88. username = #{username,jdbcType=VARCHAR},
  89. </if>
  90. <if test="password != null">
  91. password = #{password,jdbcType=VARCHAR},
  92. </if>
  93. </set>
  94. where id = #{id,jdbcType=VARCHAR}
  95. </update>
  96. <update id="updateByPrimaryKey" parameterType="com.sica.domain.User">
  97. update user
  98. set username = #{username,jdbcType=VARCHAR},
  99. password = #{password,jdbcType=VARCHAR}
  100. where id = #{id,jdbcType=VARCHAR}
  101. </update>
  102. </mapper></span>

之后,我扩展了一个 Dao 接口,当然,你也可以直接使用 mapper 接口,都是一样的。
Dao 接口
IUserDao

  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.dao;
  2. import com.sica.mapper.UserMapper;
  3. /**
  4. * Created by IntelliJ IDEA.
  5. * Package: com.sica.dao
  6. * Name: IUserDao
  7. * User: xiang.li
  8. * Date: 2015/5/22
  9. * Time: 15:25
  10. * Desc: To change this template use File | Settings | File Templates.
  11. */
  12. public interface IUserDao extends UserMapper {
  13. }</span>

下面就是 service 和实现层的代码了。
IUserService

  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.service;
  2. import com.sica.domain.User;
  3. import java.util.List;
  4. /**
  5. * Created by xiang.li on 2015/1/31.
  6. */
  7. public interface IUserService {
  8. /**
  9. * 根据Id查询用户对象
  10. * @param id 编号
  11. * @return 用户对象
  12. */
  13. User getUserById(String id);
  14. /**
  15. * 根据用户名查询用户对象
  16. * @return List
  17. */
  18. List<User> queryUserList();
  19. }</span>

UserServiceImpl

  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.service.impl;
  2. import com.sica.dao.IUserDao;
  3. import com.sica.domain.User;
  4. import com.sica.service.IUserService;
  5. import org.springframework.stereotype.Service;
  6. import javax.annotation.Resource;
  7. import java.util.List;
  8. /**
  9. * Created by xiang.li on 2015/1/31.
  10. */
  11. @Service("userService")
  12. public class UserServiceImpl implements IUserService {
  13. @Resource
  14. public IUserDao userDao;
  15. @Override
  16. public User getUserById(String id) {
  17. return this.userDao.selectByPrimaryKey(id);
  18. }
  19. @Override
  20. public List<User> queryUserList() {
  21. return userDao.queryForList();
  22. }
  23. }</span>

当然,还有所谓的 applicationContext.xml 配置,不过,我这里叫 spring-mybatis.xml。

  1. <span style="font-family:Comic Sans MS;font-size:12px;"><?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/mvc
  12. http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  13. <!-- 自动扫描 -->
  14. <context:component-scan base-package="com.sica"/>
  15. <!-- 引入配置文件 -->
  16. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
  17. p:location="classpath:jdbc.properties"
  18. />
  19. <!-- 配置数据库连接池 -->
  20. <!-- 初始化连接大小 -->
  21. <!-- 连接池最大数量 -->
  22. <!-- 连接池最大空闲 -->
  23. <!-- 连接池最小空闲 -->
  24. <!-- 获取连接最大等待时间 -->
  25. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
  26. p:driverClassName="${jdbc.driver}"
  27. p:url="${jdbc.url}"
  28. p:username="${jdbc.username}"
  29. p:password="${jdbc.password}"
  30. p:initialSize="${jdbc.initialSize}"
  31. p:maxActive="${jdbc.maxActive}"
  32. p:maxIdle="${jdbc.maxIdle}"
  33. p:minIdle="${jdbc.minIdle}"
  34. p:maxWait="${jdbc.maxWait}"
  35. />
  36. <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
  37. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" lazy-init="default"
  38. p:dataSource-ref="dataSource"
  39. p:mapperLocations="classpath:com/sica/mapping/*.xml"
  40. />
  41. <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
  42. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
  43. p:basePackage="com.sica.dao"
  44. p:sqlSessionFactoryBeanName="sqlSessionFactory"
  45. />
  46. <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
  47. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  48. p:dataSource-ref="dataSource"
  49. />
  50. </beans></span>

最后,我用到的是 junit 进行的测试,测试代码如下。
GetUserTest

  1. <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.user;
  2. import com.alibaba.fastjson.JSON;
  3. import com.sica.domain.User;
  4. import com.sica.service.IUserService;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.test.context.ContextConfiguration;
  10. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  11. import javax.annotation.Resource;
  12. import java.util.List;
  13. /**
  14. * Created by xiang.li on 2015/2/1.
  15. */
  16. @RunWith(SpringJUnit4ClassRunner.class)
  17. @ContextConfiguration(locations = "classpath:spring-mybatis.xml")
  18. public class GetUserTest {
  19. private static String UUID = "3";
  20. @Resource
  21. private IUserService userService;
  22. private static Logger logger = LoggerFactory.getLogger(GetUserTest.class);
  23. @Test
  24. public void test() {
  25. User user = userService.getUserById(UUID);
  26. logger.info(JSON.toJSONString(user));
  27. }
  28. /**
  29. * 测试联合查询
  30. */
  31. @Test
  32. public void test2() {
  33. List<User> users = userService.queryUserList();
  34. logger.info(JSON.toJSONString(users));
  35. }
  36. }</span>

测试结果

可以看到,所有的用户和用户对应的角色都全部查出来了,这说明,这次的测试很成功。

关于优化

对于优化嘛,我这里简单的提几点,大家可以考虑一下。首先,就是对表的设计,在设计表初期,不仅仅要考虑到数据库的规范性,还好考虑到所谓的业务,以及对性能的影响,比如,如果从规范性角度考虑的话,可能就会分多个表,但是如果从性能角度来考虑的话,庞大的数据量在多表联合查询的时候,相对于单表来说,就会慢很多,这时,如果字段不是很多的话,可以考虑冗余几个字段采用单表的设计。
其次嘛,就是在 sql 上下功夫了,对于联合查询,sql 的优化是很有必要的,到底是采用 INNER JOIN,还是采用 LEFT JOIN 亦或是 RIGHT JOIN 、OUTTER JOIN 等,都是要在满足业务需求之后,通过测试性能得出的结论。
再次嘛,就是在程序中调用的时候了,是采用懒加载,还是采用非懒加载的方式,这也算是一个因素吧,具体的还是要考虑业务的需要。
最后嘛,就要用到数据库的缓存了,或者在数据库与程序的中间再加一层缓存。不过,还是建议用好数据库本身自带的缓存功能。

到此这篇关于MyBatis 多表联合查询及优化的文章就介绍到这了,更多相关MyBatis 多表联合查询内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号