1. 程式人生 > >2.select查詢用法

2.select查詢用法

import config exc 直接 return nbsp 方法 tis strong

1.定義查詢接口

UserMapper.java

package tk.mybatis.simple.mapper;

import tk.mybatis.simple.model.SysRole;
import tk.mybatis.simple.model.SysUser;

import java.util.List;

/**
 * @author weihu
 * @date 2018/8/3/003 0:01
 */
public interface UserMapper {
    /**
     * 通過id查詢用戶,selectById()方法名與配置的xml文件中的id一致
     */
    SysUser selectById(Long id);

    
/** * 查詢全部用戶 */ List<SysUser> selectAll(); List<SysRole> selectRolesByUserId(Long userId); }

2.配置對應的xml文件

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
"> <!--sql語句映射文件--> <!--因為已經配置了別名,所以resultType可以直接寫類名,沒有配置的話就要寫類全名--> <mapper namespace="tk.mybatis.simple.mapper.UserMapper"> <resultMap id="userMap" type="tk.mybatis.simple.model.SysUser"> <id property="id" column="id"/> <result property="userName
" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="userEmail" column="user_email"/> <result property="userInfo" column="user_info"/> <result property="headImg" column="head_img"/> <result property="createTime" column="create_time"/> </resultMap> <select id="selectById" resultMap="userMap"> SELECT * from sys_user WHERE id=#{id} </select> <select id="selectAll" resultType="tk.mybatis.simple.model.SysUser"> SELECT id, user_name userName, user_password userPassword, user_email userEmail, user_info userInfo, head_img headImg, create_time createTime FROM sys_user </select> <select id="selectRolesByUserId" resultType="tk.mybatis.simple.model.SysRole"> select r.id, r.role_name roleName, r.enabled, r.create_by createBy, r.create_time createTime, u.user_name as "user.userName", u.user_email as "user.userEmail" from sys_user u inner join sys_user_role ur on u.id=ur.user_id inner join sys_role r on ur.role_id=r.id where u.id=#{userId} </select> </mapper>

<select>:映射查詢語句使用的標簽

id:命名空間的唯一標識符,可用來代表這條語句

resultMap:用於設置返回值的類型和映射關系

#{id}:MyBatis SQL中使用預編譯參數的一種方式

property:對應實體類字段

column:對應數據庫字段

3.實體類

SysUser.java

package tk.mybatis.simple.model;

import java.util.Arrays;
import java.util.Date;

/**
 * @author weihu
 * @date 2018/8/2/002 23:22
 * @desc SysUser實體類
 */
public class SysUser {
    private Long id;
    private String userName;
    private String userPassword;
    private String userEmail;
    private String userInfo;
    private byte[] headImg;
    private Date createTime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

    public String getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(String userInfo) {
        this.userInfo = userInfo;
    }

    public byte[] getHeadImg() {
        return headImg;
    }

    public void setHeadImg(byte[] headImg) {
        this.headImg = headImg;
    }

    public Date getCreateTime() {
        return createTime;
    }

    @Override
    public String toString() {
        return "SysUser{" +
                "id=" + id +
                ", userName=‘" + userName + \‘ +
                ", userPassword=‘" + userPassword + \‘ +
                ", userEmail=‘" + userEmail + \‘ +
                ", userInfo=‘" + userInfo + \‘ +
                ", headImg=" + Arrays.toString(headImg) +
                ", createTime=" + createTime +
                };
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

4.BaseMapperTest.java

package tk.mybatis.simple.mapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;

import java.io.IOException;
import java.io.Reader;

/**
 * @author weihu
 * @date 2018/8/4/004 17:58
 * @desc 基礎測試類
 */
public class BaseMapperTest {
    private static SqlSessionFactory sqlSessionFactory;
    @BeforeClass
    public static void init(){
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //獲取sqlSession
    public SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

UserMapperTest.java

package tk.mybatis.simple.mapper;

import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.Test;
import tk.mybatis.simple.model.SysRole;
import tk.mybatis.simple.model.SysUser;

import java.util.List;

/**
 * @author weihu
 * @date 2018/8/5/005 9:34
 * @desc
 */
public class UserMapperTest extends BaseMapperTest {

    /**
     * 根據Id查詢用戶信息
     */
    @Test
    public void testSelectById(){
        SqlSession sqlSession = getSqlSession();
        try {
            //獲取UserMapper接口
         UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            SysUser sysUser = userMapper.selectById(1L);
            System.out.println(sysUser);
            System.out.println(sysUser.getUserName());
            System.out.println(sysUser.getCreateTime());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }


    }

    /**
     * 查詢所有用戶信息
     */
    @Test
    public void selectAllUserTest() {
        SqlSession sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<SysUser> sysUsers = userMapper.selectAll();
            //遍歷用戶列表
            for (SysUser user:sysUsers){
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

    }

    @Test
    public void testSelectRolesByUserId(){
        SqlSession sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<SysRole> roleList = userMapper.selectRolesByUserId(1L);
            System.out.println(roleList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

    }
}

多表關聯查詢

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">
<!--sql語句映射文件-->

<!--因為已經配置了別名,所以resultType可以直接寫類名,沒有配置的話就要寫類全名-->
<mapper namespace="tk.mybatis.simple.mapper.UserMapper">

    <select id="selectRolesByUserId" resultType="tk.mybatis.simple.model.SysRole">
        select
            r.id,
            r.role_name roleName,
            r.enabled,
            r.create_by createBy,
            r.create_time createTime,
            u.user_name as "user.userName",
            u.user_email as "user.userEmail"
        from sys_user u
        inner join sys_user_role ur on u.id=ur.user_id
        inner join sys_role r on ur.role_id=r.id
        where u.id=#{userId}
    </select>
</mapper>

註意:

u.user_name as "user.userName",
u.user_email as "user.userEmail"
這裏設置別名的時候,使用的是"user.屬性名",user是SysRole中增加的屬性,userName和userEmail是SysUer對象中的屬性

SysRole.java
package tk.mybatis.simple.model;

import java.util.Date;

/**
 * @author weihu
 * @date 2018/8/2/002 23:19
 * @desc
 */
public class SysRole {
    private Long id;
    private String roleName;
    private int enabled;
    private String createBy;
    private Date createTime;

    private SysUser user;

    public SysUser getUser() {
        return user;
    }

    public void setUser(SysUser user) {
        this.user = user;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public int getEnabled() {
        return enabled;
    }

    public void setEnabled(int enabled) {
        this.enabled = enabled;
    }

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

 
UserMapperTest.class
package tk.mybatis.simple.mapper;

import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.Test;
import tk.mybatis.simple.model.SysRole;
import tk.mybatis.simple.model.SysUser;

import java.util.List;

/**
 * @author weihu
 * @date 2018/8/5/005 9:34
 * @desc
 */
public class UserMapperTest extends BaseMapperTest {

  /**
     * 多表查詢
     */
    @Test
    public void testSelectRolesByUserId(){
        SqlSession sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<SysRole> roleList = userMapper.selectRolesByUserId(1L);
            System.out.println(roleList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

    }
}

2.select查詢用法