今天碰到了一个问题,就是要在三张表里面各取一部分数据然后组成一个list传到前台页面显示。但是并不想在后台做太多判断,(因为涉及到for循环)会拉慢运行速度。正好用的框架是spring+springMVC+mybatis,所以很自然的就想到了联表查询。

一开始认为mybatis编写语句很简单,但是在编写的时候遇到了一些细节问题,所以发文记录一下。

先说一下背景:

框架:spring+springMVC+mybatis

表结构:

1、主表

2、从表

从表的uid对应主表的id,并将主表的id设为主键

接下来开始解析代码

先用mybatis的generator自动生成dao、mapper、model层

model层如下:

User.java

package am.model;

import java.util.List;

public class User {

    private Integer id;

    private String username;

    private String pwd;

    private List<Student> students;

    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 == null ? null : username.trim();

    }

    public String getPwd() {

        return pwd;

    }

    public void setPwd(String pwd) {

        this.pwd = pwd == null ? null : pwd.trim();

    }

        public List<Student> getStudents() {

                return students;

        }

        public void setStudents(List<Student> students) {

                this.students = students;

        }

}

  

Student.java

package am.model;

public class Student {

    private Integer id;

    private String position;

    private String level;

    private Integer uid;

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getPosition() {

        return position;

    }

    public void setPosition(String position) {

        this.position = position == null ? null : position.trim();

    }

    public String getLevel() {

        return level;

    }

    public void setLevel(String level) {

        this.level = level == null ? null : level.trim();

    }

    public Integer getUid() {

        return uid;

    }

    public void setUid(Integer uid) {

        this.uid = uid;

    }

}

  

需要注意的是在User表里面添加了成员变量

private List<Student> students;

  

这是因为联表查询时Student表为从表,你最终要将得到的数据放在主表User里

mapping层

UserMapper.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="am.dao.UserMapper" >

  <resultMap id="BaseResultMap" type="am.model.User" >

    <id column="id" property="id" jdbcType="INTEGER" />

    <result column="username" property="username" jdbcType="VARCHAR" />

    <result column="pwd" property="pwd" jdbcType="VARCHAR" />

  </resultMap>

  <resultMap id="studentForListMap" type="am.model.User" >

    <id column="id" property="id" jdbcType="INTEGER" />

    <result column="username" property="username" jdbcType="VARCHAR" />

    <result column="pwd" property="pwd" jdbcType="VARCHAR" />

    <collection property="students" javaType="java.util.List" ofType="am.model.Student"> 

            <result column="id" property="id" jdbcType="INTEGER" />

                    <result column="position" property="position" jdbcType="VARCHAR" />

                    <result column="level" property="level" jdbcType="VARCHAR" /> 

    </collection>

  </resultMap>

  <select id="studentForList" resultMap="studentForListMap" >

    select u.id,u.username,u.pwd,s.position,s.level from user u left join student s on u.id = s.uid

  </select>

  <sql id="Base_Column_List" >

    id, username, pwd

  </sql>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >

    select

    <include refid="Base_Column_List" />

    from user

    where id = #{id,jdbcType=INTEGER}

  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >

    delete from user

    where id = #{id,jdbcType=INTEGER}

  </delete>

  <insert id="insert" parameterType="am.model.User" >

    insert into user (id, username, pwd

      )

    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR}

      )

  </insert>

  <insert id="insertSelective" parameterType="am.model.User" >

    insert into user

    <trim prefix="(" suffix=")" suffixOverrides="," >

      <if test="id != null" >

        id,

      </if>

      <if test="username != null" >

        username,

      </if>

      <if test="pwd != null" >

        pwd,

      </if>

    </trim>

    <trim prefix="values (" suffix=")" suffixOverrides="," >

      <if test="id != null" >

        #{id,jdbcType=INTEGER},

      </if>

      <if test="username != null" >

        #{username,jdbcType=VARCHAR},

      </if>

      <if test="pwd != null" >

        #{pwd,jdbcType=VARCHAR},

      </if>

    </trim>

  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="am.model.User" >

    update user

    <set >

      <if test="username != null" >

        username = #{username,jdbcType=VARCHAR},

      </if>

      <if test="pwd != null" >

        pwd = #{pwd,jdbcType=VARCHAR},

      </if>

    </set>

    where id = #{id,jdbcType=INTEGER}

  </update>

  <update id="updateByPrimaryKey" parameterType="am.model.User" >

    update user

    set username = #{username,jdbcType=VARCHAR},

      pwd = #{pwd,jdbcType=VARCHAR}

    where id = #{id,jdbcType=INTEGER}

  </update>

</mapper>

  

需要注意

1、property="students"中的students必须与User.java中的private List<Student> students;中的students命名一样

2、resultMap="studentForListMap"必须与<resultMap id="studentForListMap" type="am.model.User" >中的id一致

<resultMap id="studentForListMap" type="am.model.User" >

    <id column="id" property="id" jdbcType="INTEGER" />

    <result column="username" property="username" jdbcType="VARCHAR" />

    <result column="pwd" property="pwd" jdbcType="VARCHAR" />

    <collection property="students" javaType="java.util.List" ofType="am.model.Student"> 

            <result column="id" property="id" jdbcType="INTEGER" />

                    <result column="position" property="position" jdbcType="VARCHAR" />

                    <result column="level" property="level" jdbcType="VARCHAR" /> 

    </collection>

  </resultMap>

  <select id="studentForList" resultMap="studentForListMap" >

    select u.id,u.username,u.pwd,s.position,s.level from user u left join student s on u.id = s.uid

  </select>

  

dao层

UserMapper.java

package am.dao;

import java.util.List;

import am.model.User;

public interface UserMapper {

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> queryForList();

    List<User> studentForList();

}

  

spring-mybatis.xml

<?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-3.1.xsd 

                        http://www.springframework.org/schema/context 

                        http://www.springframework.org/schema/context/spring-context-3.1.xsd 

                        http://www.springframework.org/schema/mvc 

                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

        <!-- 自动扫描 -->

        <context:component-scan base-package="am.*" />

        <!-- 引入配置文件 -->

        <bean id="propertyConfigurer"

                class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

                <property name="location" value="classpath:jdbc.properties" />

        </bean>

        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

                destroy-method="close">

                <property name="driverClassName" value="${driver}" />

                <property name="url" value="${url}" />

                <property name="username" value="${username}" />

                <property name="password" value="${password}" />

                <!-- 初始化连接大小 -->

                <property name="initialSize" value="${initialSize}"></property>

                <!-- 连接池最大数量 -->

                <property name="maxActive" value="${maxActive}"></property>

                <!-- 连接池最大空闲 -->

                <property name="maxIdle" value="${maxIdle}"></property>

                <!-- 连接池最小空闲 -->

                <property name="minIdle" value="${minIdle}"></property>

                <!-- 获取连接最大等待时间 -->

                <property name="maxWait" value="${maxWait}"></property>

        </bean>

        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->

        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

                <property name="dataSource" ref="dataSource" />

                <!-- 自动扫描mapping.xml文件 -->

                <property name="mapperLocations" value="classpath:am/mapping/*.xml"></property>

        </bean>

        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->

        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

                <property name="basePackage" value="am.dao" />

                <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

        </bean>

        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->

        <bean id="transactionManager"

                class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

                <property name="dataSource" ref="dataSource" />

        </bean>

</beans>

  

我用serviceImp层来继承service层实现dao层,当然你也可以直接实现dao层,在这里就不多做赘述了。

分享一下项目包结构:

最后做一点简单的测试

MybatisController

package am.controller;

import java.util.List;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import am.model.User;

import am.service.UserService;

@Controller 

@RequestMapping("/my")

public class MybatisController {

        @Resource

        private UserService userService;

        @RequestMapping("/t") 

         public ModelAndView test(HttpServletRequest request){ 

                 ModelAndView view = new ModelAndView("test");

                 List<User> users = userService.studentForList();

                 String s = JSON.toJSONString(users);

                 System.out.println(JSON.toJSONString(users));

                 return view;

         }

}

  

success,得到想要数据。

mybatis之联表查询的更多相关文章

  1. Mybatis框架-联表查询显示问题解决

    需求:查询结果要求显示用户名,用户密码,用户的角色 因为在用户表中只有用户角色码值,没有对应的名称,角色名称是在码表smbms_role表中,这时我们就需要联表查询了. 这里需要在User实体类中添加 ...

  2. mybatis一对一联表查询的两种常见方式

    1.一条语句执行查询(代码如下图)  注释:class表(c别名),teacher表(t别名)teacher_id为class表的字段t_id为teacher表的字段,因为两者有主键关联的原因,c_i ...

  3. MyBatis联表查询

    MyBatis逆向工程主要用于单表操作,那么需要进行联表操作时,往往需要我们自己去写sql语句. 写sql语句之前,我们先修改一下实体类 Course.java: public class Cours ...

  4. mybatis 联表查询

    一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关 ...

  5. MyBatis学习存档(5)——联表查询

    之前的数据库操作都是基于一张表进行操作的,若一次查询涉及到多张表,那该如何进行操作呢? 首先明确联表查询的几个关系,大体可以分为一对一和一对多这两种情况,接下来对这两种情况进行分析: 一.建立表.添加 ...

  6. Mybatis入门(四)------联表查询

    Mybatis联表查询 一.1对1查询 1.数据库建表 假设一个老师带一个学生 CREATE TABLE teacher( t_id INT PRIMARY KEY, t_name VARCHAR(3 ...

  7. MyBatis实现关联表查询

    一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关 ...

  8. MyBatis——实现关联表查询

    原文:http://www.cnblogs.com/xdp-gacl/p/4264440.html 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创 ...

  9. Spring Hibernate JPA 联表查询 复杂查询(转)

    今天刷网,才发现: 1)如果想用hibernate注解,是不是一定会用到jpa的? 是.如果hibernate认为jpa的注解够用,就直接用.否则会弄一个自己的出来作为补充. 2)jpa和hibern ...

随机推荐

  1. IDEA添加Lombok插件

    背景: 最近老大给了一个项目,是个雏.一看实体类就懵逼了,没有getter.setter和构造方法,导致service和controller全报红线,私有属性也没有注释.按规矩,心里先把这位前辈骂10 ...

  2. 解析之Apache解析

  3. 【机器学习】Jackknife,Bootstraping, bagging, boosting, AdaBoosting, Rand forest 和 gradient boosting

    Jackknife,Bootstraping, bagging, boosting, AdaBoosting, Rand forest 和 gradient boosting 这些术语,我经常搞混淆, ...

  4. DataGridView中的ComboboxCell报了System.ArgumentException:DagaGridViewComboBoxCell值无效错误

    原因是初始化的时候给ComboboxCell绑定了一系列的值,但是真正赋值的时候却给了一个不在那一系列值范围中的值,所以就报了这个错 在开发的时候难免会因为数据的问题出现这个问题,为了不让系统崩掉,就 ...

  5. PHP 调用shell命令

    可以使用的命令: popenfpassthrushell_execexecsystem 1.popen resource popen ( string command, string mode ) 打 ...

  6. windows terminal编译实录

    直接甩个大佬链接吧 https://www.bilibili.com/video/av52032233?t=835 安装过程中如果出问题了,靠搜索引擎解决下,微软或者vs的问题可以用biying搜索 ...

  7. js中的alert弹出框文字乱码解决方案

    使用如下代码即可: echo '<html>'; echo '<head><meta http-equiv="Content-Type" conten ...

  8. yii自定义验证

    自定义验证类 class BaseModel extends Model { public function rules() { return [ ['obj', ContentSecurityVal ...

  9. Maven之私服配置

    一.配置从私服下载 从私服下载主要是将 central 库的下载地址从https://repo1.maven.org/maven2/修改为私服地址,比如http://localhost:8081/re ...

  10. python之json操作

    1.json.dumps()用于将dict类型的数据转成str 备注:文件路径前面加上 r 是为了避免转义 1 import json 2 3 dict = {'a': 'wo', 'b': 'zai ...