MyBatis 多表联合查询及优化 以及自定义返回结果集
里,我已经搭好了开发的环境,用到的是 SpringMVC + Spring +
MyBatis,当然,为了简单期间,你可以不用搭前端的框架,只使用 Spring + MyBatis 就可以,外加 junit
测试即可。环境我就不带大家搭了,这里只说涉及到联合查询的操作。
- <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.domain;
- import java.io.Serializable;
- import java.util.List;
- public class User implements Serializable {
- private String id;
- private String username;
- private String password;
- private List<Role> roles;
- private static final long serialVersionUID = 1L;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id == null ? null : id.trim();
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username == null ? null : username.trim();
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password == null ? null : password.trim();
- }
- public List<Role> getRoles() {
- return roles;
- }
- public void setRoles(List<Role> roles) {
- this.roles = roles;
- }
- @Override
- public boolean equals(Object that) {
- if (this == that) {
- return true;
- }
- if (that == null) {
- return false;
- }
- if (getClass() != that.getClass()) {
- return false;
- }
- User other = (User) that;
- return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
- && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
- && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()));
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
- result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
- result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode());
- return result;
- }
- }</span>
Role
- <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.domain;
- import java.io.Serializable;
- public class Role implements Serializable {
- private String id;
- private String name;
- private String jsms;
- private String bz;
- private Integer jlzt;
- private String glbm;
- private String userid;
- private static final long serialVersionUID = 1L;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id == null ? null : id.trim();
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name == null ? null : name.trim();
- }
- public String getJsms() {
- return jsms;
- }
- public void setJsms(String jsms) {
- this.jsms = jsms == null ? null : jsms.trim();
- }
- public String getBz() {
- return bz;
- }
- public void setBz(String bz) {
- this.bz = bz == null ? null : bz.trim();
- }
- public Integer getJlzt() {
- return jlzt;
- }
- public void setJlzt(Integer jlzt) {
- this.jlzt = jlzt;
- }
- public String getGlbm() {
- return glbm;
- }
- public void setGlbm(String glbm) {
- this.glbm = glbm == null ? null : glbm.trim();
- }
- public String getUserid() {
- return userid;
- }
- public void setUserid(String userid) {
- this.userid = userid == null ? null : userid.trim();
- }
- @Override
- public boolean equals(Object that) {
- if (this == that) {
- return true;
- }
- if (that == null) {
- return false;
- }
- if (getClass() != that.getClass()) {
- return false;
- }
- Role other = (Role) that;
- return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
- && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
- && (this.getJsms() == null ? other.getJsms() == null : this.getJsms().equals(other.getJsms()))
- && (this.getBz() == null ? other.getBz() == null : this.getBz().equals(other.getBz()))
- && (this.getJlzt() == null ? other.getJlzt() == null : this.getJlzt().equals(other.getJlzt()))
- && (this.getGlbm() == null ? other.getGlbm() == null : this.getGlbm().equals(other.getGlbm()))
- && (this.getUserid() == null ? other.getUserid() == null : this.getUserid().equals(other.getUserid()));
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
- result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
- result = prime * result + ((getJsms() == null) ? 0 : getJsms().hashCode());
- result = prime * result + ((getBz() == null) ? 0 : getBz().hashCode());
- result = prime * result + ((getJlzt() == null) ? 0 : getJlzt().hashCode());
- result = prime * result + ((getGlbm() == null) ? 0 : getGlbm().hashCode());
- result = prime * result + ((getUserid() == null) ? 0 : getUserid().hashCode());
- return result;
- }
- }</span>
- <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.mapper;
- import com.sica.domain.User;
- import java.util.List;
- public interface UserMapper {
- int deleteByPrimaryKey(String id);
- int insert(User record);
- int insertSelective(User record);
- User selectByPrimaryKey(String id);
- int updateByPrimaryKeySelective(User record);
- int updateByPrimaryKey(User record);
- List<User> queryForList();
- }</span>
- <span style="font-family:Comic Sans MS;font-size:12px;"><?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.sica.mapper.UserMapper">
- <resultMap id="BaseResultMap" type="com.sica.domain.User">
- <id column="id" property="id" jdbcType="VARCHAR"/>
- <result column="username" property="username" jdbcType="VARCHAR"/>
- <result column="password" property="password" jdbcType="VARCHAR"/>
- </resultMap>
- <resultMap id="queryForListMap" type="com.sica.domain.User">
- <id column="id" property="id" jdbcType="VARCHAR"/>
- <result column="username" property="username" jdbcType="VARCHAR"/>
- <result column="password" property="password" jdbcType="VARCHAR"/>
- <collection property="roles" javaType="java.util.List" ofType="com.sica.domain.Role">
- <id column="r_id" property="id" jdbcType="VARCHAR" />
- <result column="r_name" property="name" jdbcType="VARCHAR" />
- <result column="r_jsms" property="jsms" jdbcType="VARCHAR" />
- <result column="r_bz" property="bz" jdbcType="VARCHAR" />
- <result column="r_jlzt" property="jlzt" jdbcType="INTEGER" />
- <result column="r_glbm" property="glbm" jdbcType="VARCHAR" />
- </collection>
- </resultMap>
- <select id="queryForList" resultMap="queryForListMap">
- SELECT
- u.id,
- u.username,
- u.password,
- r.id r_id,
- r.name r_name,
- r.jsms r_jsms,
- r.bz r_bz,
- r.jlzt r_jlzt,
- r.glbm r_glbm
- FROM
- user u
- LEFT JOIN
- role r
- ON
- u.id = r.userid
- </select>
- <sql id="Base_Column_List">
- id, username, password
- </sql>
- <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String">
- select
- <include refid="Base_Column_List"/>
- from user
- where id = #{id,jdbcType=VARCHAR}
- </select>
- <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
- delete from user
- where id = #{id,jdbcType=VARCHAR}
- </delete>
- <insert id="insert" parameterType="com.sica.domain.User">
- insert into user (id, username, password
- )
- values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
- )
- </insert>
- <insert id="insertSelective" parameterType="com.sica.domain.User">
- insert into user
- <trim prefix="(" suffix=")" suffixOverrides=",">
- <if test="id != null">
- id,
- </if>
- <if test="username != null">
- username,
- </if>
- <if test="password != null">
- password,
- </if>
- </trim>
- <trim prefix="values (" suffix=")" suffixOverrides=",">
- <if test="id != null">
- #{id,jdbcType=VARCHAR},
- </if>
- <if test="username != null">
- #{username,jdbcType=VARCHAR},
- </if>
- <if test="password != null">
- #{password,jdbcType=VARCHAR},
- </if>
- </trim>
- </insert>
- <update id="updateByPrimaryKeySelective" parameterType="com.sica.domain.User">
- update user
- <set>
- <if test="username != null">
- username = #{username,jdbcType=VARCHAR},
- </if>
- <if test="password != null">
- password = #{password,jdbcType=VARCHAR},
- </if>
- </set>
- where id = #{id,jdbcType=VARCHAR}
- </update>
- <update id="updateByPrimaryKey" parameterType="com.sica.domain.User">
- update user
- set username = #{username,jdbcType=VARCHAR},
- password = #{password,jdbcType=VARCHAR}
- where id = #{id,jdbcType=VARCHAR}
- </update>
- </mapper></span>
- <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.dao;
- import com.sica.mapper.UserMapper;
- /**
- * Created by IntelliJ IDEA.
- * Package: com.sica.dao
- * Name: IUserDao
- * User: xiang.li
- * Date: 2015/5/22
- * Time: 15:25
- * Desc: To change this template use File | Settings | File Templates.
- */
- public interface IUserDao extends UserMapper {
- }</span>
- <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.service;
- import com.sica.domain.User;
- import java.util.List;
- /**
- * Created by xiang.li on 2015/1/31.
- */
- public interface IUserService {
- /**
- * 根据Id查询用户对象
- * @param id 编号
- * @return 用户对象
- */
- User getUserById(String id);
- /**
- * 根据用户名查询用户对象
- * @return List
- */
- List<User> queryUserList();
- }</span>
UserServiceImpl
- <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.service.impl;
- import com.sica.dao.IUserDao;
- import com.sica.domain.User;
- import com.sica.service.IUserService;
- import org.springframework.stereotype.Service;
- import javax.annotation.Resource;
- import java.util.List;
- /**
- * Created by xiang.li on 2015/1/31.
- */
- @Service("userService")
- public class UserServiceImpl implements IUserService {
- @Resource
- public IUserDao userDao;
- @Override
- public User getUserById(String id) {
- return this.userDao.selectByPrimaryKey(id);
- }
- @Override
- public List<User> queryUserList() {
- return userDao.queryForList();
- }
- }</span>
当然,还有所谓的 applicationContext.xml 配置,不过,我这里叫 spring-mybatis.xml。
- <span style="font-family:Comic Sans MS;font-size:12px;"><?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc.xsd">
- <!-- 自动扫描 -->
- <context:component-scan base-package="com.sica"/>
- <!-- 引入配置文件 -->
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
- p:location="classpath:jdbc.properties"
- />
- <!-- 配置数据库连接池 -->
- <!-- 初始化连接大小 -->
- <!-- 连接池最大数量 -->
- <!-- 连接池最大空闲 -->
- <!-- 连接池最小空闲 -->
- <!-- 获取连接最大等待时间 -->
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
- p:driverClassName="${jdbc.driver}"
- p:url="${jdbc.url}"
- p:username="${jdbc.username}"
- p:password="${jdbc.password}"
- p:initialSize="${jdbc.initialSize}"
- p:maxActive="${jdbc.maxActive}"
- p:maxIdle="${jdbc.maxIdle}"
- p:minIdle="${jdbc.minIdle}"
- p:maxWait="${jdbc.maxWait}"
- />
- <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" lazy-init="default"
- p:dataSource-ref="dataSource"
- p:mapperLocations="classpath:com/sica/mapping/*.xml"
- />
- <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
- p:basePackage="com.sica.dao"
- p:sqlSessionFactoryBeanName="sqlSessionFactory"
- />
- <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
- p:dataSource-ref="dataSource"
- />
- </beans></span>
GetUserTest
- <span style="font-family:Comic Sans MS;font-size:12px;">package com.sica.user;
- import com.alibaba.fastjson.JSON;
- import com.sica.domain.User;
- import com.sica.service.IUserService;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import javax.annotation.Resource;
- import java.util.List;
- /**
- * Created by xiang.li on 2015/2/1.
- */
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = "classpath:spring-mybatis.xml")
- public class GetUserTest {
- private static String UUID = "3";
- @Resource
- private IUserService userService;
- private static Logger logger = LoggerFactory.getLogger(GetUserTest.class);
- @Test
- public void test() {
- User user = userService.getUserById(UUID);
- logger.info(JSON.toJSONString(user));
- }
- /**
- * 测试联合查询
- */
- @Test
- public void test2() {
- List<User> users = userService.queryUserList();
- logger.info(JSON.toJSONString(users));
- }
- }</span>
测试结果
出自:http://blog.csdn.net/happylee6688/article/details/45967763
MyBatis 多表联合查询及优化 以及自定义返回结果集的更多相关文章
- MyBatis 多表联合查询,字段重复的解决方法
MyBatis 多表联合查询,两张表中字段重复时,在配置文件中,sql语句联合查询时使用字段别名,resultMap中对应的column属性使用相应的别名: <resultMap type=&q ...
- MyBatis之三:多表联合查询
在这篇文章里面主要讲解如何在mybatis里面使用一对一.一对多.多表联合查询(类似视图)操作的例子. 注:阅读本文前请先大概看一下之前两篇文章. 一.表结构 班级表class,学生表student, ...
- Mybatis oracle多表联合查询分页数据重复的问题
Mybatis oracle多表联合查询分页数据重复的问题 多表联合查询分页获取数据时出现一个诡异的现象:数据总条数正确,但有些记录多了,有些记录却又少了甚至没了.针对这个问题找了好久,最后发现是由于 ...
- mybatis:开发环境搭建--增删改查--多表联合查询(多对一)
什么是mybatisMyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyBatis使用简单的XML或 ...
- mybatis Plus 多表联合查询
//实体类package com.sk.skkill.entity; import com.baomidou.mybatisplus.annotation.TableField;import com. ...
- 一步步学Mybatis-实现多表联合查询(4)
上一章节中我们已经完成了对单表的CRUD操作,接下来今天这一讲讲述的是关于Mybatis在多表查询时候的应用,毕竟实际业务中也是多表的联合查询比较多嘛~ 还记得最一开始我们新建过一张Website表吗 ...
- 你了解MySQL中的多表联合查询吗?
前言: 多表联合查询,其实就是我们MySQL中的join语句,经常会看到有人说join非常影响性能,不建议使用,你知道这是为什么呢?我们究竟可不可以用呢? 测试数据: CREATE TABLE `t2 ...
- yii 多表联合查询的几种方法
yii多表联合查询, 第一种,用command,自己拼接sql语句执行查询 第二种,用AR,model需继承下面的ar,执行queryall或queryrow方法 <?php //applica ...
- MVC5+EF6简单实例---以原有SQLServer数据库两表联合查询为例
有二三年没写代码了,**内的工作就是这样,容易废人!看到园子里这么多大侠朝气蓬勃的,我想也要学点东西并和大家分享,共同进步!快乐每一天,进步每一天!言归正传! 通过最近一段时间对MVC5.EF6的学习 ...
随机推荐
- 三层架构与MVC的区别
我们平时总是将混为一谈,殊不知它俩并不是一个概念.下面我来为大家揭晓我所知道的一些真相. 首先,它俩根本不是一个概念. 三层架构是一个分层式的软件体系架构设计,它可适用于任何一个项目. MVC是一个设 ...
- Spark实战1:shell+独立App使用总结
Spark改进了Hadoop执行非流式算法的需要多次IO的缺陷,Spark的所有操作都是基于RDD弹性分布式数据集这种数据结构的,对RDD的操作主要的操作包括transform和action两种操作. ...
- ctl 里面pdef解说
WRF 模式MM5 模式都是目前从网上可以下载的气象软件,因此在国内经常可以见到.但这两种模式的数据特点数据的水平网格都不是标准的经纬度网格.需要在ctl 文件中加入PDEF 定义说明把这种非标准的数 ...
- C# csv 操作类
using System.Data; using System.IO; using System.Text; namespace YanZhiwei.DotNet2.Utilities.Common ...
- n阶乘 尾数0的个数
class Solution {public: int trailingZeroes(int n) { if(n<=0) return 0; int i=0; ...
- linux打开文件数量的查看方法
linux打开文件数量的查看方法 linux打开文件数量的查看方法在网上查到两种查看linux打开文件数量的查看方法,但结果不相同,linux查看文件打开数量是以那个文件或命令为标准呢? 搜索过关于u ...
- weblogic .NoClassDefFoundError: Could not initialize class sun.awt.X11Graphi
这个是常见问题,可以通过增加Weblogic的启动参数来解决: -Djava.awt.headless=true 你可以修改 startWebLogic.sh 文件. export JAVA_OPTI ...
- php socket通信(tcp/udp)
注意 1.在socket_bind的时候ip地址不能真回环地址如127.0.0.1 2.server.php后台跑起来的时候 nohup php server.php > /var/tmp/a. ...
- 关于Oracle过程,函数的经典例子及解析
一,Oracle中的过程,函数 对于oracle中的过程和函数,个人觉得可以化为一类,因为它们在写法上并没有什么的不同.公式无非就是 create or replace Package_name(pa ...
- Oracle绑定变量
select * from table where id = ? 类似于上面这样的sql,如果不用绑定变量,每次执行时Oracle会认为是不同的sql,会在每次执行时生成一遍执行计划,而执行计划的生成 ...