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查询用法的更多相关文章

  1. 数据库中增加操作insert into的用法和查询select的用法

    insert into的用法 1.一条insert into 可以插入多条记录 2.insert into 能判断主键是否冲突,和做出冲突处理 如果主键冲突的话会报错,还能写成如果冲突就更新的形式格式 ...

  2. Select查询命令

    一开始SELECT查询的命令为     SELECT * FROM employee;     SELECT 要查询的列名 FROM 表名字 WHERE 限制条件;     若要查询所有内容,就用*代 ...

  3. MyBatis基础入门《四》接口方式.Select查询集合

    MyBatis基础入门<四>接口方式.Select查询集合 描述: 在<MyBatis基础入门<二>Select查询>中有说过,SQLSession有两种用法,这里 ...

  4. mysql union 和 left join 结合查询用法

    union 和 left join 结合查询用法 SELECT u.nickname,z.group_comming_type,z.id,z.user_id,z.title,z.create_time ...

  5. mysql DML select查询

    windows上的操作 1.从官网下载mysql 下载navicat,用来连接mysql的 2.打开运行启动mysql 3.在navicat上的连接打开新建连接 然后输入链接名,连接名就是用户名,自己 ...

  6. mysql子查询用法

    mysql子查询用法 1 可以当值来用<pre>select id from hcyuyin_share where id=(select id from hcyuyin_share li ...

  7. 5- MySQL数据库SELECT查询操作

    复习: 数据类型: 数值型:整数(int,tinyint,smallint,bigint,mediumint) 浮点型(float ,double,decimal) 字符型:char(固定长度) ,v ...

  8. 关于SubSonic3.0插件使用SqlQuery或Select查询时产生的System.NullReferenceException异常修复

    早上在编写执行用例时,突然爆异常System.NullReferenceException: 未将对象引用设置到对象的实例 执行代码:

  9. 为什么忘记commit也会造成select查询的性能问题

    今天遇到一个很有意思的问题,一个开发人员反馈在测试服务器ORACLE数据库执行的一条简单SQL语句非常缓慢,他写的一个SQL没有返回任何数据,但是耗费了几分钟的时间.让我检查分析一下原因,分析解决过后 ...

随机推荐

  1. C/C++常用预处理指令

    预处理是在编译之前的处理,而编译工作的任务之一就是语法检查,预处理不做语法检查.预处理命令以符号“#”开头. 常用的预处理指令包括: 宏定义:#define 文件包含:#include 条件编译:#i ...

  2. KeyPress键盘按键ASCII值对应表

    vbKeyLButton 1 鼠标左键  vbKeyRButton 2 鼠标右键  vbKeyCancel 3 CANCEL 键  vbKeyMButton 4 鼠标中键  vbKeyBack 8 B ...

  3. Robotframework与unittest对比

    都可以自动挂ui测试 都可以自动化接口测试

  4. 用 Python 写 Robot Framework 测试

    Robot Framework 框架是基于 Python 语言开发的,所以,它本质上是 Python 的一个库. 1.你懂 Python 语言. 2.又想使用 Robot Framework 测试框架 ...

  5. Spring相关知识点

    1.注解@qualifier 只能注在属性上 作用:当一个接口有多个实现类时,用Autowired装配时,因为Autowired是按类型装配的(Resource按名称),所以多个实现类会出现冲突,这是 ...

  6. android 使用webview 加载网页

    1. <WebView android:id="@+id/webView" android:layout_width="fill_parent" andr ...

  7. windows server 2008 - 隐藏磁盘分区 (2)

    二 创建策略并设置给指定用户 1 打开“组策略管理”(在这里创建策略) cmd下输入GPMC.MSC 打开组策略管理   随后在域上右键选择“在这个域中创建GPO并在此处链接”,输入名字“磁盘管理策略 ...

  8. kbmMW均衡负载与容灾(3)(转载红鱼儿)

    在kbmMW均衡负载与容灾(1)中,介绍了利用ClientTransport的OnReconnect事件,对联接的应用服务器的地址进行更换,做容灾处理.实际上,作者还给我们提供了另外一种机制,直接在C ...

  9. kbmMW均衡负载与容灾(2)(转载红鱼儿)

    集中式均衡负载 为实现集中式均衡负载方案,需要实现两个不同的应用服务器,一个是只包含均衡负载组件再无其他内容的应用服务器,可称之为均衡负载应用服务器,下文简称LB Server,另外一个就是包含一个或 ...

  10. 717. 1-bit and 2-bit Characters

    static int wing=[]() { std::ios::sync_with_stdio(false); cin.tie(NULL); ; }(); class Solution { publ ...