MyBatis单表查询

本例将描述一张表的CRUD,其中表结构为:

CREATE TABLE `message`.`user` 
( 
`id` INT NOT NULL AUTO_INCREMENT , 
`username` VARCHAR(20) NOT NULL , 
`password` VARCHAR(20) NOT NULL , 
PRIMARY KEY (`id`) 
) 
ENGINE = InnoDB;    

javabean

package cn.elinzhou.bean;

/**
 * Created by 烽 on 2015/6/4.
 */
public class User {
    private int id;
    private String username;
    private String password;

    public User(){}

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
  • 首先,在已经搭建好MyBatis环境的基础下,新建一个cn.elinzhou.config.sql包。
  • 创建一个user.xml文件,在其中加入如下信息
<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="User">

</mapper>

其中,为该配置文件的命名空间,而所有对User表的所有操作都在这里完成,需要保证在整个项目下命名空间唯一

  • 在命名空间中写一个查询标签,并写入最简单的无条件查询
<select id="queryAll" resultMap="UserResult">
    SELECT id,username,password FROM user WHERE 1=1
</select>

select标签中有三个参数,分别是id、resultMap,表示操作标识,返回值类型。
其中操作标识需要在同一命名空间下唯一,可以任意取
返回值类型就是要返回的模型,也可以说是javabean,当然,这个是自己定义的,所以在该命名空间下加入如下代码

<resultMap id="UserResult" type="cn.elinzhou.bean.User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="username" jdbcType="String" property="username"/>
    <result column="password" jdbcType="String" property="password"/>
</resultMap>

首先,resultMap标签有两个属性,一个是标识,同样是同命名空间下唯一,另一个是类型,是该模型的javabean,需要写全路径。
resultMap有两个子标签,分别为id和result,两个唯一的区别是id用来描述主键,result用来描述非主键,其中的参数完全相同,所以以result为例:
result三个标签,column表示从数据库中查询返回的列名;jdbcType表示该字段的类型,如果不是java.lang下的类需要写全路径;property表示对应javabean中的变量名

  • 数据表配置文件写完,就需要把它加入到核心配置文件也就是Configuration.xml中;在configuration标签中添加
<mappers>
  <mapper resource="cn/elinzhou/config/sql/User.xml"/>
</mappers>

以后的每一张表配置文件都要添加到mappers标签下。

  • 然后可以直接调用之前获取到的sqlsession,获取数据。
sqlSession.selectList("User.queryAll");

这样,将获得一个对应的javabean数组。

  • 在查询过程中往往是需要传入查询参数的,这里举三个例子,一个是通过基本数据类型查询,一个通过自定义类查询,一个通过list查询
  • 首先通过基本数据类型查询,这里对 User中的id查询。在User.xml中加入如下代码
<select id="queryByID" parameterType="int" resultMap="UserResult">
    SELECT id,username,password FROM user WHERE id = #{_parameter}
</select>

其中与之前不同的第一点是参数多了一个parameterType,表示传入的参数类型,基本数据类型直接写类型名,自定义类或非java.lang下的类写全路径。
这里传入的是int型的id,所以sql需要修改,最后的变量位置写#{_parameter},#{}为MyBatis规定的,其中的值同ognl表达式。
具体写法整理如下:(来自慕课网)
这里写图片描述这里写图片描述

业务代码为

sqlSession.selectList("User.queryByID"5);
  • 有时候查询条件不唯一,但是MyBatis只能传入一个参数,所以需要把查询数据封装起来。这里举一个不合实际的例子,但是为了演示需要,通过username和password查询id
<select id="queryByBean" parameterType="cn.elinzhou.bean.User" resultMap="UserResult">
    SELECT id,username,password
    FROM user
    WHERE 1=1
    <if test="username != null and !&quot;&quot;.equals(username.trim())">
        AND username = #{username}
    </if>
    <if test="password != null and !&quot;&quot;.equals(password.trim())">
        AND password LIKE '%' #{password} '%'
    </if>
</select>

此时传入的是一个自定义类,所以parameterType要写该类的全路径,静态sql语句部分不解释了,主要讲动态拼接部分。
MyBatis的配置文件的逻辑控制主要通过OGNL表达式,由于这里查询条件存在不确定性,所以需要进行判断,通过if标签,根据test属性中得到的布尔值来进行控制。而test中的代码完全等同于java代码,只是一些特殊的符号需要转义,如上述演示代码中的&quot ; &quot ; 为转义后的“”
业务代码为

sqlSession.selectList("User.queryByBean"new User(0,"Tom","1234"));
  • 通过list查询,假设现在需要查询指定id的用户
<select id="queryByIDs" parameterType="java.util.ArrayList" resultMap="UserResult">
    SELECT id,username,password 
    FROM user 
    WHERE id IN (
        <foreach collection="list" item="item" separator=",">
            #{item}
        </foreach>
    )
</select>

跟之前的差别主要是用了foreach标签,其作用为遍历集合,其中collection为要遍历的对象,item为每一个遍历到的元素的变量名,separator为元素之前的分割字符,sql中分割是用’,‘分割。
业务代码为

sqlSession.selectList("User.queryByIDs",Arrays.asList(1,2,3));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值