mybatis入门篇:Mapper接口/关联查询/新增数据
1、数据准备
2、编写实体类
package com.forest.owl.entity; import java.util.Date; public class User { private Long id; private String userName; private String userPassword; private String userPhone; private String userEmail; private byte[] headImg; private Date createTime; private Date updateTime; 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 getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public byte[] getHeadImg() { return headImg; } public void setHeadImg(byte[] headImg) { this.headImg = headImg; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
3、编写相对应的Mapper接口
package com.forest.owl.mapper; import com.forest.owl.entity.User; import java.util.List; public interface UserMapper { User selectUserById(Long id); List<User> selectAllUser(); }
4、编写UserMapper.xml
在resources中加入文件夹com/forest/owl/mapper,在此文件夹中添加UserMapper文件
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.forest.owl.mapper.UserMapper"> <resultMap id="userMap" type="com.forest.owl.entity.User"> <id property="id" column="id" /> <result property="userName" column="user_name" /> <result property="userPassword" column="user_password" /> <result property="userPhone" column="user_phone" /> <result property="userEmail" column="user_email" /> <result property="headImg" column="head_img" jdbcType="BLOB" /> <result property="createTime" column="create_time" jdbcType="TIMESTAMP" /> <result property="updateTime" column="update_time" jdbcType="TIMESTAMP" /> </resultMap> <select id="selectUserById" resultMap="userMap"> SELECT * FROM user WHERE id=#{id} </select> <select id="selectAllUser" resultType="com.forest.owl.entity.User"> SELECT id, user_name, user_password, user_phone, user_email, head_img, create_time, update_time FROM user </select> </mapper>
5、修改mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <package name="com.forest.owl.entity"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <dataSource type="UNPOOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/forest?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <package name="com.forest.owl.mapper"/> </mappers> </configuration>
6、编写测试代码
package com.forest.owl; import com.forest.owl.entity.User; 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; 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(); } } public SqlSession getSqlSession(){ SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; } }
package com.forest.owl; import com.forest.owl.entity.User; import com.forest.owl.mapper.UserMapper; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class MapperTest extends BaseMapperTest{ @Test public void UserMapperTest(){ SqlSession sqlSession = getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUserById((long) 3); System.out.println(user.getUserName()); List<User> userList = userMapper.selectAllUser(); userList.stream().forEach(i -> System.out.println(i.getUserName())); } }
7、关联查询
假设在用户信息查询的基础上,我还想查询用户的角色与权限,该如何?
首先定义角色与权限的实体类
package com.forest.owl.entity; import java.util.Date; public class Role { private Long id; private String roleName; private int enabled; private Long createBy; private Date createTime; private Long updateBy; private Date updateTime; 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 Long getCreateBy() { return createBy; } public void setCreateBy(Long createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getUpdateBy() { return updateBy; } public void setUpdateBy(Long updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
package com.forest.owl.entity; import java.util.Date; public class Privilege { private Long id; private String privilegeName; private String privilegeUrl; private Long createBy; private Date createTime; private Long updateBy; private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPrivilegeName() { return privilegeName; } public void setPrivilegeName(String privilegeName) { this.privilegeName = privilegeName; } public String getPrivilegeUrl() { return privilegeUrl; } public void setPrivilegeUrl(String privilegeUrl) { this.privilegeUrl = privilegeUrl; } public Long getCreateBy() { return createBy; } public void setCreateBy(Long createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getUpdateBy() { return updateBy; } public void setUpdateBy(Long updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
在User实体类中添加Role与Privilege属性
private Role role; private Privilege privilege; public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Privilege getPrivilege() { return privilege; } public void setPrivilege(Privilege privilege) { this.privilege = privilege; }
修改UserMapper.xml文件
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.forest.owl.mapper.UserMapper"> <resultMap id="userMap" type="com.forest.owl.entity.User"> <id property="id" column="id" /> <result property="userName" column="user_name" /> <result property="userPassword" column="user_password" /> <result property="userPhone" column="user_phone" /> <result property="userEmail" column="user_email" /> <result property="headImg" column="head_img" jdbcType="BLOB" /> <result property="createTime" column="create_time" jdbcType="TIMESTAMP" /> <result property="updateTime" column="update_time" jdbcType="TIMESTAMP" /> <association property="role"> <result property="roleName" column="role_name" /> </association> <association property="privilege"> <result property="privilegeName" column="privilege_name" /> <result property="privilegeUrl" column="privilege_url" /> </association> </resultMap> <select id="selectUserById" resultMap="userMap"> SELECT u.*, r.role_name, p.privilege_name, p.privilege_url FROM user u INNER JOIN user_role ur on ur.user_id=u.id INNER JOIN role r on r.id=ur.role_id INNER JOIN role_privilege rp on rp.role_id=r.id INNER JOIN privilege p on p.id=rp.privilege_id WHERE u.id=#{id} </select> <select id="selectAllUser" resultType="com.forest.owl.entity.User"> SELECT u.id, u.user_name, u.user_password, u.user_phone, u.user_email, u.head_img, u.create_time, u.update_time, r.role_name as "role.roleName", p.privilege_name as "privilege.privilegeName", p.privilege_url as "privilege.privilegeUrl" FROM user u INNER JOIN user_role ur on ur.user_id=u.id INNER JOIN role r on r.id=ur.role_id INNER JOIN role_privilege rp on rp.role_id=r.id INNER JOIN privilege p on p.id=rp.privilege_id </select> </mapper>
编写测试类
@Test public void UserMapperTest(){ SqlSession sqlSession = getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUserById((long) 3); System.out.println(user.getUserName()); System.out.println(user.getRole().getRoleName()); System.out.println(user.getPrivilege().getPrivilegeName()); System.out.println(user.getPrivilege().getPrivilegeUrl()); List<User> userList = userMapper.selectAllUser(); userList.stream().forEach(i -> { System.out.println(i.getUserName()); System.out.println(i.getRole().getRoleName()); System.out.println(i.getPrivilege().getPrivilegeName()); System.out.println(i.getPrivilege().getPrivilegeUrl()); }); }
8、新增数据
在UserMapper接口中新增方法
int insertUser(User user);
UserMapper.xml
<insert id="insertUser"> INSERT INTO user (user_name, user_password, user_phone, user_email, head_img, create_time, update_time) VALUES( #{userName}, #{userPassword}, #{userPhone}, #{userEmail}, #{headImg}, #{createTime}, #{updateTime} ) </insert>
测试代码
@Test public void UserMapperTest(){ SqlSession sqlSession = getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = new User(); user.setUserName("新用户名"); user.setUserPassword("密码"); user.setUserPhone("手机号"); user.setUserEmail("邮箱号"); int result = userMapper.insertUser(user); System.out.println(result); sqlSession.commit(); }
因为SqlSessionFactory.openSession()是不自动提交的,故此处需要手动提交,否则无效。
对于想要得到插入数据的主键,可以设置mybatis-config.xml的配置项useGeneratedKeys为true
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="useGeneratedKeys" value="true"/> </settings>
然后在<insert />配置中添加keyProperty="id",在数据插入成功后,mybatis会将主键回写至id里,届时使用user.getId()获取即可。
<insert id="insertUser" keyProperty="id"> INSERT INTO user (user_name, user_password, user_phone, user_email, head_img, create_time, update_time) VALUES( #{userName}, #{userPassword}, #{userPhone}, #{userEmail}, #{headImg}, #{createTime}, #{updateTime} ) </insert>
mybatis入门篇:Mapper接口/关联查询/新增数据的更多相关文章
- mybatis入门篇:通过SqlSession.selectList进行数据查询
作为一个java菜鸟,早就从慕课网中学到一些基本的mybatis的用法,但是一直不成体系,懵懵懂懂,既然正式入了java这个坑,就打算好好学学,所以买了本<MyBatis从入门到精通>,在 ...
- Mybatis学习总结四(关联查询)
一.一对一查询 实例:查询所有订单信息,关联查询下单用户信息. Method1:使用resultType,定义订单信息po类,此po类中包括了订单信息和用户信息. public class Order ...
- mybatis如何根据mapper接口生成其实现类
SpringBoot集成mybatis mybatis的statement的解析与加载 mybatis如何根据mapper接口生成其实现类 mybatis的mapper返回map结果集 mybatis ...
- idea插件(mybatis框架下mapper接口快速跳转对应xml文件)亲测好用!
我相信目前在绝大部分公司里,主要使用的框架是S(spring)S(spring MVC)M(mybatis),其中mybatis总体架构是编写mapper接口,框架扫描其对应的mapper.xml文件 ...
- mybatis入门篇:Mybatis高级查询
1.ResultMap的association与collection association与collection功能类似,区别是一对一与一对多,这里以association为例. 首先说明一下需求: ...
- MyBatis入门学习教程-实现关联表查询
一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关 ...
- Mybatis入门篇之结果映射,你射准了吗?
目录 前言 什么是结果映射? 如何映射? 别名映射 驼峰映射 配置文件开启驼峰映射 配置类中开启驼峰映射 resultMap映射 总结 高级结果映射 关联(association) 例子 关联的嵌套 ...
- MyBatis入门篇
一.什么是MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改 ...
- mybatis入门篇:Mybatis注解方式的基本用法
@Select 1.mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?> <! ...
随机推荐
- Java 猜字谜游戏
package fundmental_excise6; import java.util.Arrays; import java.util.Scanner; /** * @author : jeasi ...
- css3 二级菜单
<!doctype html><!--<!DOCTYPE> 声明位于文档中的最前面的位置,处于 <html> 标签之前.此标签可告知浏览器文档使用哪种 HTM ...
- Android 音视频深入 九 FFmpeg解码视频生成yuv文件(附源码下载)
项目地址,求star https://github.com/979451341/Audio-and-video-learning-materials/tree/master/FFmpeg(MP4%E8 ...
- 在Tomcat中部署Web项目的操作方法,maven项目在Tomcat里登录首页报404
maven项目在Tomcat里登录首页报404, 解决:编辑conf/server.xml进行配置<Host>里的<Context>标签里的path. <Context ...
- 学习java的第4天 (2019-03-21 11:49)
学习java的第4天 好文要顶 关注我 收藏该文 里里零关注 - 0粉丝 - 0 0 0 posted on 2019-03-21 11:49 编辑 抱歉! ...
- 野(wild)指针与悬空(dangling)指针
1. 什么是野指针(wild pointer)? A pointer in c which has not been initialized is known as wild pointer. 野指针 ...
- useradd语法2
在Linux中 useradd 命令用来创建或更新用户信息. useradd 命令属于比较难用的命令 (low level utility for adding users),所以 Debian 系的 ...
- mybatis xml配置文件模版
mybatis xml配置文件模版 1.mybatis核心配置文件书写(SqlMapConfig.xml) <?xml version="1.0" encoding=&quo ...
- 3.1 unittest简介
3.1 unittest简介 前言 熟悉java的应该都清楚常见的单元测试框架Junit和TestNG.python里面也有单元测试框架-unittest,相当于是一个python版的junit.py ...
- Java方法 传值方式
这个问题是面试的时候经常会问到的一道题吧?这次做项目的过程中,其中一个同学因为无用了,导致了一个bug,不过是在提测前啦!本来我想借着这次机会分享一下java方法传参的机制,但是经过几天的学习,了解, ...