2.select查询用法

时间:2024-04-22 11:05:23

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();
} }
}