MyBatis知识总结和梳理(2)
MyBatis知识总结和梳理(2)
Mybatis映射
本文为上课时实例,篇幅较长,请耐心阅览
1 映射文件XXMapper.xml语法:
<mapper namespace="cn.smbms.dao.user.UserMapper">
<select id="getUserList" …
……
</select>
</mapper>
1.1 namespace:命名空间
namespace的命名必须跟某个接口同名
1.2 id: 命名空间中唯一的标识符
接口中的方法与映射文件中的SQL语句id一一对应
1.3 parameterType: 参数类型
传入SQL语句的参数类型
1.4 resultType:返回值类型
SQL语句返回值类型的完整类名或别名
1.5 实战:
需求:根据用户名对用户表进行模糊查询
1.6 实现:
(1)导入库
smbms_db.sql
(2)创建工程,目录
(3)pom
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
(4)实体类
package cn.kgc.entity;
public class User {
private Integer id;
private String userCode;
private String userName;
private String userPassword;
private Integer gender;
private String birthday;
private String phone;
private String address;
private Integer userRole;
private Integer createdBy;
private String creationDate;
private Integer modifyBy;
private String modifyDate;
private String userRoleName;
public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
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 Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public String getModifyDate() {
return modifyDate;
}
public void setModifyDate(String modifyDate) {
this.modifyDate = modifyDate;
}
}
(5)mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/smbms"/>
<property name="username" value="root"/>
<property name="password" value="ok"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/kgc/mapper/UserMapper.xml"/>
</mappers>
</configuration>
(6)mapper/UserMapper.java
package cn.kgc.mapper;
import cn.kgc.entity.User;
import java.util.List;
public interface UserMapper {
public List<User> findByName(String userName);
}
(7)mapper/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="cn.kgc.mapper.UserMapper">
<select id="findByName" parameterType="java.lang.String" resultType="cn.kgc.entity.User">
select * from smbms_user where userName like concat('%',#{userName},'%')
</select>
</mapper>
(8)MyBatisUtil
package cn.smbms.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
private static SqlSessionFactory factory;
static{//在静态代码块下,factory只会被创建一次
System.out.println("static factory===============");
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession createSqlSession(){
return factory.openSession(false);//true 为自动提交事务
}
public static void closeSqlSession(SqlSession sqlSession){
if(null != sqlSession)
sqlSession.close();
}
}
(9)TestUserMapper.java
package cn.kgc.test;
import cn.kgc.entity.User;
import cn.kgc.mapper.UserMapper;
import cn.kgc.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class TestUserMapper {
@Test
public void testfindByName() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
List<User> list = sqlSession.getMapper(UserMapper.class).findByName("孙");
for(User u:list){
System.out.println("用户名称:"+u.getUserName()+" 用户密码:"+u.getUserPassword());
}
sqlSession.close();
}
}
1.7 parameterType 基础数据类型/复杂数据类型
parameterType
(1)基础数据类型:
int、String、Date等
只能传入一个,通过#{参数名}即可获取传入的值
(2)复杂数据类型:
Java实体类、Map等
通过#{属性名}或者#{map的keyName}即可获取传入值
1.8 多参实战:
需求:通过用户名模糊匹配和用户角色id 条件查询
1.9第一种实现:
(1)UserMapper.java
public List<User> findAllByUser(User user);
(2)UserMapper.xml
<select id="findAllByUser" parameterType="cn.kgc.entity.User" resultType="cn.kgc.entity.User">
select * from smbms_user where userName like concat('%',#{userName},'%')
and userRole = #{userRole}
</select>
(3)TestUserMapper
@Test
public void testfindAllByUser() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
User user = new User();
user.setUserName("孙");
user.setUserRole(5);
List<User> list = sqlSession.getMapper(UserMapper.class).findAllByUser(user);
for(User u:list){
System.out.println("用户名称:"+u.getUserName()+" 用户密码:"+u.getUserPassword());
}
sqlSession.close();
}
1.10第二种实现:
(1)UserMapper.java
public List<User> findAllByMap(Map<String,String> map);
(2)UserMapper.xml
<select id="findAllByMap" parameterType="java.util.Map" resultType="cn.kgc.entity.User">
select * from smbms_user where userName like concat('%',#{userName},'%')
and userRole = #{userRole}
</select>
(3)TestUserMapper
@Test
public void testfindAllByMap() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
Map map =new HashMap<>();
map.put("userName","孙");
map.put("userRole","5");
List<User> list = sqlSession.getMapper(UserMapper.class).findAllByMap(map);
for(User u:list){
System.out.println("用户名称:"+u.getUserName()+" 用户密码:"+u.getUserPassword());
}
sqlSession.close();
}
1.11 resultMap 描述如何将结果集映射到Java对象
resultType :直接表示返回类型
基本数据类型
复杂数据类型
resultMap :对外部resultMap的引用
应用场景:
数据库字段信息与对象属性不一致
复杂的联合查询,*控制映射结果
二者不能同时存在,本质上都是Map数据结构
1.12 通过用户名和角色编码查询用户列表
(1)User.java
private String userRoleName;
public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
(2)UserMapper.java
public List<User> findAllByUser2(User user);
(3)UserMapper.xml
<select id="findAllByUser2" parameterType="cn.kgc.entity.User" resultMap="userList">
select u.*,r.roleName from smbms_user u,smbms_role r
where u.userName like CONCAT ('%',#{userName},'%')
and u.userRole = #{userRole} and u.userRole = r.id
</select>
<resultMap id="userList" type="cn.kgc.entity.User">
<result property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="phone" column="phone"/>
<result property="birthday" column="birthday"/>
<result property="gender" column="gender"/>
<result property="userRole" column="userRole"/>
<result property="userRoleName" column="roleName"/>
</resultMap>
(4)TestUserMapper.java
@Test
public void testfindAllByUser2() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
User user = new User();
user.setUserName("孙");
user.setUserRole(3);
List<User> list = sqlSession.getMapper(UserMapper.class).findAllByUser2(user);
for(User u:list){
System.out.println("用户名称:"+u.getUserName()+" 用户密码:"+u.getUserPassword()+" 用户角色:"+u.getUserRoleName());
}
sqlSession.close();
}
2.增删改
核心注意点:
insert、update、delete元素均没有resultType属性
(1)实现用户表的增加操作
public Integer addUser(User user);
<insert id="addUser" parameterType="cn.kgc.entity.User">
insert into smbms_user (userCode,userName,userPassword,gender,birthday,phone,
address,userRole,createdBy,creationDate)
values (#{userCode},#{userName},#{userPassword},#{gender},#{birthday},#{phone},
#{address},#{userRole},#{createdBy},#{creationDate})
</insert>
@Test
public void testaddUser() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
User user = new User();
user.setUserCode("test001");
user.setUserName("测试用户001");
user.setUserPassword("1234567");
user.setGender(1);
user.setBirthday("2011-01-01");
user.setPhone("13688783697");
user.setAddress("地址测试");
user.setUserRole(1);
user.setCreatedBy(1);
user.setCreationDate("2022-03-04");
user.setModifyBy(33);
user.setModifyDate("2029-01-03");
int flag = sqlSession.getMapper(UserMapper.class).addUser(user);
if(flag>0){
System.out.println("添加成功");
}
sqlSession.commit();
sqlSession.close();
}
(2)实现用户表的修改操作
public Integer updateUser(User user);
<update id="updateUser" parameterType="cn.kgc.entity.User">
update smbms_user set userCode = #{userCode},userName= #{userName},userPassword= #{userPassword},gender= #{gender},birthday= #{birthday},phone= #{phone},
address= #{address},userRole= #{userRole},createdBy= #{createdBy},creationDate= #{creationDate}
where id = #{id}
</update>
@Test
public void testupdateUser() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
User user = new User();
user.setId(1);
user.setUserCode("test002");
user.setUserName("测试用户001");
user.setUserPassword("1234567");
user.setGender(1);
user.setBirthday("2011-01-01");
user.setPhone("13688783697");
user.setAddress("地址测试");
user.setUserRole(1);
user.setCreatedBy(1);
user.setCreationDate("2022-03-04");
user.setModifyBy(33);
user.setModifyDate("2029-01-03");
int flag = sqlSession.getMapper(UserMapper.class).updateUser(user);
if(flag>0){
System.out.println("添加成功");
}
sqlSession.commit();
sqlSession.close();
}
(3)实现修改当前用户密码的功能[email protected]
核心思想:
超过三个参数建议封装成对象,两个参数建议使用@Param
public Integer updatePwd(@Param("userPassword")String userPassword,@Param("id")Integer id);
<update id="updatePwd" parameterType="cn.kgc.entity.User">
update smbms_user set userPassword = #{userPassword}
where id = #{id}
</update>
@Test
public void testupdatePwd() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
// String userPassword,@Param("id")Integer id
String userPassword = "9999";
Integer id = 1;
int flag = sqlSession.getMapper(UserMapper.class).updatePwd(userPassword,id);
if(flag>0){
System.out.println("添加成功");
}
sqlSession.commit();
sqlSession.close();
}
(4)根据用户id删除用户信息
public Integer delById(Integer id);
<delete id="delById" parameterType="java.lang.Integer">
delete from smbms_user where id = #{id}
</delete>
@Test
public void testdelById() throws IOException {
SqlSession sqlSession = MyBatisUtil.createSqlSession();
Integer id = 1;
int flag = sqlSession.getMapper(UserMapper.class).delById(id);
if(flag>0){
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
3.resultMap
核心思想
id
一般对应数据库中该行的主键id,设置此项可提高MyBatis性能
result
映射到JavaBean的某个“简单类型”属性
association
映射到JavaBean的某个“复杂类型”属性,比如JavaBean类
collection
映射到JavaBean的某个“复杂类型”属性,比如集合
(1)根据用户角色id获取用户列表-association
A.核心思想:
association
复杂的类型关联,一对一
内部嵌套
映射一个嵌套JavaBean属性
属性
property:映射数据库列的实体对象的属性
javaType:完整Java类名或者别名
resultMap:引用外部resultMap
子元素
id
result
property:映射数据库列的实体对象的属性
column:数据库列名或者别名
B.实战:
Role:
package cn.smbms.pojo;
import java.util.Date;
public class Role {
private Integer id; //id
private String roleCode; //角色编码
private String roleName; //角色名称
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate;//更新时间
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
User
package cn.smbms.pojo;
import java.util.Date;
public class User {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色ID
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer age;//年龄
//private String userRoleName; //用户角色名称
//association
private Role role; //用户角色
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Integer getAge() {
/*long time = System.currentTimeMillis()-birthday.getTime();
Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/
Date date = new Date();
Integer age = date.getYear()-birthday.getYear();
return age;
}
/* public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}*/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
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 Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
UserMapper
/**
* 根据roleId获取用户列表
* @param roleId
* @return
*/
public List<User> getUserListByRoleId(@Param("userRole")Integer roleId);
<select id="getUserListByRoleId" parameterType="Integer" resultMap="userRoleResult">
select u.*,r.id as r_id,r.roleCode,r.roleName from smbms_user u,smbms_role r
where u.userRole = #{userRole} and u.userRole = r.id
</select>
<resultMap type="User" id="userRoleResult">
<id property="id" column="id"/>
<result property="userCode" column="userCode" />
<result property="userName" column="userName" />
<result property="userRole" column="userRole" />
<association property="role" javaType="Role" >
<id property="id" column="r_id"/>
<result property="roleCode" column="roleCode"/>
<result property="roleName" column="roleName"/>
</association>
</resultMap>
(2)获取指定用户的相关信息及其地址列表-collection
A核心思想:
collection
复杂类型集合,一对多
内部嵌套
映射一个嵌套结果集到一个列表
属性
property:映射数据库列的实体对象的属性
ofType:完整Java类名或者别名(集合所包括的类型)
resultMap:引用外部resultMap
子元素
id
result
property:映射数据库列的实体对象的属性
column:数据库列名或者别名
B实战:
1.Address
package cn.smbms.pojo;
import java.util.Date;
public class Address {
private Integer id; //主键ID
private String postCode; //邮编
private String contact; //联系人
private String addressDesc; //地址
private String tel; //联系电话
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer userId; //用户ID
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getAddressDesc() {
return addressDesc;
}
public void setAddressDesc(String addressDesc) {
this.addressDesc = addressDesc;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
User
package cn.smbms.pojo;
import java.util.Date;
import java.util.List;
public class User {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色ID
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer age;//年龄
//private String userRoleName; //用户角色名称
//association
private Role role; //用户角色
//collection
private List<Address> addressList;//用户地址列表
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> addressList) {
this.addressList = addressList;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Integer getAge() {
/*long time = System.currentTimeMillis()-birthday.getTime();
Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/
Date date = new Date();
Integer age = date.getYear()-birthday.getYear();
return age;
}
/* public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}*/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
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 Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
2.mapper,xml
/**
* 获取指定用户的地址列表(collection)
* @param userId
* @return
*/
public List<User> getAddressListByUserId(@Param("id")Integer userId);
<select id="getAddressListByUserId" parameterType="Integer" resultMap="userAddressResult">
select u.*,a.id as a_id,a.contact,a.addressDesc,a.postCode,a.tel
from smbms_user u,smbms_address a where u.id = a.userId and u.id=#{id}
</select>
<!-- 获取指定用户的地址列表(user表-address表:1对多关系) collection start-->
<resultMap type="User" id="userAddressResult">
<id property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<collection property="addressList" ofType="Address">
<id property="id" column="a_id"/>
<result property="postCode" column="postCode"/>
<result property="tel" column="tel"/>
<result property="contact" column="contact"/>
<result property="addressDesc" column="addressDesc"/>
</collection>
</resultMap>
上一篇: 【Java】基础知识笔记