建立对象关系映射。
<resultMap id="userResultMap" type="user">
<id column="uid" property="id">id>
<result column="NAME" property="username">result>
<result column="PASSWORD" property="username">result>
resultMap>
<select id="findAllResultMap" resultMap="userResultMap">
SELECT id AS uid,username AS NAME,password AS PASSWORD FROM USER
select>
需求:根据 id 和 username 查询 user 表。
使用 #{arg0}-#{argn} 或者 #{param1}-#{paramn} 获取参数。
UserMapper 接口
public interface UserMapper {
public List<User> findByIdAndUsername1(Integer id, String username);
}
UserMapper.xml
<mapper namespace="com.lagou.mapper.UserMapper">
<select id="findByIdAndUsername1" resultType="user">
select * from user where id = #{param1} and username = #{param2}
select>
mapper>
测试
@Test
public void testFindByIdAndUsername() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findByIdAndUsername1(41, "老王");
System.out.println(list);
}
使用注解,引入 @Param() 注解获取参数。
UserMapper 接口
public interface UserMapper {
public List<User> findByIdAndUsername2(@Param("id") Integer id,@Param("username") String username);
}
UserMapper.xml
<mapper namespace="com.lagou.mapper.UserMapper">
<select id="findByIdAndUsername2" resultType="user">
select * from user where id = #{id} and username = #{username}
select>
mapper>
测试
@Test
public void testFindByIdAndUsername() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findByIdAndUsername2(41, "老王");
System.out.println(list);
}
使用pojo 对象传递参数
UserMapper 接口
public interface UserMapper {
public List<User> findByIdAndUsername3(User user);
}
UserMapper.xml
<mapper namespace="com.lagou.mapper.UserMapper">
<select id="findByIdAndUsername3" parameterType="com.lagou.domain.User" resultType="com.lagou.domain.User">
select * from user where id = #{id} and username = #{username}
select>
mapper>
测试
@Test
public void testFindByIdAndUsername() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User param = new User();
param.setId(41);
param.setUsername("老王");
List<User> list = userMapper.findByIdAndUsername3(41, "老王");
System.out.println(list);
}
需求:根据username 模糊查询user 表。
UserMapper 接口
public interface UserMapper {
public List<User> findByUsername1(String username);
}
UserMapper.xml
<mapper namespace="com.lagou.mapper.UserMapper">
<select id="findByUsername1" parameterType="string" resultType="user">
select * from user where username like #{username}
select>
mapper>
测试
@Test
public void testFindByUsername() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findByUsername1("%王%");
for (User user : list) {
System.out.println(user);
}
}
UserMapper 接口
public interface UserMapper {
public List<User> findByUsername2(String username);
}
UserMapper.xml
<mapper namespace="com.lagou.mapper.UserMapper">
<select id="findByUsername2" resultMap="userResultMap" parameterType="string">
select * from user where username like '${value}'
select>
mapper>
测试
@Test
public void testFindByUsername() throws Exception {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.findByUsername2("%子慕%");
for (User user : users) {
System.out.println(user);
}
}
#{}:表示一个占位符号
${}:表示拼接sql 串
应用场景
我们很多时候有这种需求,向数据库插入一条记录后,希望能立即拿到这条记录在数据库中的主键值。
public interface UserMapper {
// 返回主键
public void save(User user);
}
<insert id="save" parameterType="user" useGeneratedKeys="true" keyProperty="id">
INSERT INTO `user`(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
insert>
注意:只适用于主键自增的数据库, mysql 和sqlserver 支持, oracle 不行。
<insert id="save" parameterType="user">
<selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID();
selectKey>
INSERT INTO `user`(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
insert>
应用场景:当我们要根据不同的条件,来执行不同的 sql 语句的时候,需要用到动态sql。
需求:根据id 和username 查询,但是不确定两个都有值。
public List<User> findByIdAndUsernameIf(User user);
<select id="findByIdAndUsernameIf" parameterType="user" resultType="user">
SELECT * FROM `user`
<where>
<if test="id != null">
AND id = #{id}
if>
<if test="username != null">
AND username = #{username}
if>
where>
select>
需求:如果有id 只使用id 做查询,没有 id 的话看是否有username,有username 就根据username 做查询,如果都没有,就不带条件。
<select id="findByIdAndUsernameChoose" parameterType="user" resultType="user">
SELECT * FROM `user`
<where>
<choose>
<when test="id != null">
AND id = #{id}
when>
<when test="username != null">
AND username = #{username}
when>
<otherwise>
AND 1=1
otherwise>
choose>
where>
select>
需求:动态更新user 表数据,如果该属性有值就更新,没有值不做处理。
<update id="updateIf" parameterType="user">
UPDATE `user`
<set>
<if test="username != null">
username = #{username},
if>
<if test="birthday != null">
birthday = #{birthday},
if>
<if test="sex != null">
sex = #{sex},
if>
<if test="address != null">
address = #{address},
if>
set>
WHERE id = #{id}
update>
foreach 主要是用来做数据的循环遍历。
例如: select * from user where id in (1,2,3) 在这样的语句中,传入的参数部分必须依靠
foreach 遍历才能实现。
<foreach>标签用于遍历集合,它的属性:
• collection:代表要遍历的集合元素
• open:代表语句的开始部分
• close:代表结束部分
• item:代表遍历集合的每个元素,生成的变量名
• sperator:代表分隔符
a)集合
UserMapper 接口
public List<User> findByList(List<Integer> ids);
UserMaper.xml 映射
<select id="findByList" parameterType="list" resultType="user" >
SELECT * FROM `user`
<where>
<foreach collection="collection" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
测试代码
// foreach 标签 list
@Test
public void testFindByList() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<Integer> ids = new ArrayList<>();
ids.add(46);
ids.add(48);
ids.add(51);
List<User> list = userMapper.findByList(ids);
System.out.println(list);
}
b)数组
UserMapper 接口
public List<User> findByArray(Integer[] ids);
UserMaper.xml 映射
<select id="findByArray" parameterType="int" resultType="user">
SELECT * FROM `user`
<where>
<foreach collection="array" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
测试代码
// foreach 标签 array
@Test
public void testFindByArray() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Integer[] ids = {46, 48, 51};
List<User> list = userMapper.findByArray(ids);
System.out.println(list);
}
c)pojo
QueryVo
public class QueryVo {
private List<Integer> ids;
}
核心配置文件
<typeAliases>
<typeAlias type="com.lagou.domain.User" alias="user">typeAlias>
<typeAlias type="com.lagou.domain.QueryVo" alias="queryVo">typeAlias>
typeAliases>
UserMapper 接口
public List<User> findByPojo(QueryVo queryVo);
UserMaper.xml 映射
<select id="findByPojo" parameterType="queryVo" resultType="user">
SELECT * FROM `user`
<where>
<foreach collection="ids" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
测试代码
// foreach 标签 pojo
@Test
public void testFindByPojo() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<Integer> ids = new ArrayList<>();
ids.add(46);
ids.add(48);
ids.add(51);
QueryVo queryVo = new QueryVo();
queryVo.setIds(ids);
List<User> list = userMapper.findByPojo(queryVo);
System.out.println(list);
}
应用场景:映射文件中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的。
<sql id="selectUser">
SELECT * FROM `user`
sql>
<select id="findByList" parameterType="list" resultType="user" >
<include refid="selectUser">include>
<where>
<foreach collection="collection" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
<select id="findByArray" parameterType="integer[]" resultType="user">
<include refid="selectUser">include>
<where>
<foreach collection="array" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
MyBatis 可以使用第三方的插件来对功能进行扩展,分页助手PageHelper 是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据。
开发步骤:
①导入通用PageHelper 的坐标。
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>3.7.5version>
dependency>
<dependency>
<groupId>com.github.jsqlparsergroupId>
<artifactId>jsqlparserartifactId>
<version>0.9.1version>
dependency>
②在mybatis 核心配置文件中配置 PageHelper 插件。
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
plugin>
③测试分页代码实现。
@Test
public void testPageHelper(){
//设置分页参数
PageHelper.startPage(1,2);
List<User> select = userMapper2.select(null);
for(User user : select){
System.out.println(user);
}
}
获得分页相关的其他参数
//其他分页的数据
PageInfo<User> pageInfo = new PageInfo<User>(select);
System.out.println("总条数: " + pageInfo.getTotal());
System.out.println("总页数: " + pageInfo.getPages());
System.out.println("当前页: " + pageInfo.getPageNum());
System.out.println("每页显示长度: " + pageInfo.getPageSize());
System.out.println("是否第一页: " + pageInfo.isIsFirstPage());
System.out.println("是否最后一页: " + pageInfo.isIsLastPage());
MyBatis 核心配置文件常用标签:
关系型数据库表关系分为:
举例:
一对一查询模型:
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户。
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户。
一对一查询语句
SELECT * FROM orders o LEFT JOIN USER u ON o.`uid`=u.`id`;
1 ) Order 实体
public class Order {
private Integer id;
private Date ordertime;
private double money;
// 表示当前订单属于哪个用户
private User user;
}
2 ) OrderMapper 接口
public interface OrderMapper {
public List<Order> findAllWithUser();
}
3 ) OrderMapper.xml 映射
<resultMap id="orderMap" type="com.lagou.domain.Order">
<id column="id" property="id">id>
<result column="ordertime" property="ordertime">result>
<result column="money" property="money">result>
<association property="user" javaType="com.lagou.domain.User">
<id column="uid" property="id">id>
<result column="username" property="username">result>
<result column="birthday" property="birthday">result>
<result column="sex" property="sex">result>
<result column="address" property="address">result>
association>
resultMap>
<select id="findAllWithUser" resultMap="orderMap">
SELECT * FROM orders o LEFT JOIN USER u ON o.`uid`=u.`id`;
select>
4 )测试代码
@Test
public void testOrderWithUser() throws Exception {
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List<Order> list = orderMapper.findAllWithUser();
for (Order order : list) {
System.out.println(order);
}
}
一对多查询模型:
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户。
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单。
一对多查询语句:
SELECT *,o.id oid FROM USER u LEFT JOIN orders o ON u.`id` = o.`uid`;
1 ) User 实体
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
// 代表当前用户具备的订单列表
private List<Order> orderList;
}
2 ) UserMapper 接口
public interface UserMapper {
public List<User> findAllWithOrder();
}
3 ) UserMapper.xml 映射
<resultMap id="userMap" type="com.lagou.domain.User">
<id column="id" property="id">id>
<result column="username" property="username">result>
<result column="birthday" property="birthday">result>
<result column="sex" property="sex">result>
<result column="address" property="address">result>
<collection property="orderList" ofType="com.lagou.domain.Order">
<id column="oid" property="id">id>
<result column="ordertime" property="ordertime">result>
<result column="money" property="money">result>
collection>
resultMap>
<select id="findAllWithOrder" resultMap="userMap">
SELECT *,o.id oid FROM USER u LEFT JOIN orders o ON u.`id`=o.`uid`;
select>
4 )测试代码
@Test
public void testUserWithOrder() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findAllWithOrder();
for (User user : list) {
System.out.println(user);
}
}
多对多查询的模型:
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用。
多对多查询的需求:查询用户同时查询出该用户的所有角色。
多对多查询语句
SELECT
*
FROM
USER u -- 用户表
LEFT JOIN user_role ur -- 左外连接中间表
ON u.`id` = ur.`uid`
LEFT JOIN role r -- 左外连接中间表
ON ur.`rid` = r.`id` ;
1 ) User 和 Role 实体
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
// 代表当前用户关联的角色列表
private List<Role> roleList;
}
public class Role {
private Integer id;
private String roleName;
private String roleDesc;
}
2 ) UserMapper 接口
public interface UserMapper {
public List<User> findAllWithRole();
}
3 ) UserMapper.xml 映射
<resultMap id="userAndRoleMap" type="com.lagou.domain.User">
<id column="id" property="id">id>
<result column="username" property="username">result>
<result column="birthday" property="birthday">result>
<result column="sex" property="sex">result>
<result column="address" property="address">result>
<collection property="orderList" ofType="com.lagou.domain.Role">
<id column="rid" property="id">id>
<result column="role_name" property="roleName">result>
<result column="role_desc" property="roleDesc">result>
collection>
resultMap>
<select id="findAllWithRole" resultMap="userAndRoleMap">
SELECT * FROM USER u LEFT JOIN user_role ur ON u.`id`=ur.`uid` INNER JOIN role r ON ur.`rid` = r.`id`;
select>
4 )测试代码
@Test
public void testUserWithRole() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findAllWithRole();
for (User user : list) {
System.out.println(user);
}
}
MyBatis 多表配置方式
需求:查询一个订单,与此同时查询出该订单所属的用户
一对一查询语句
-- 先查询订单
SELECT * FROM orders;
-- 再根据订单 uid 外键,查询用户
SELECT * FROM `user` WHERE id = #{订单的uid};
1) OrderMapper 接口
public interface OrderMapper {
public List<Order> findAllWithUser();
}
2) OrderMapper.xml 映射
<resultMap id="orderMap" type="order">
<id column="id" property="id">id>
<result column="ordertime" property="ordertime">result>
<result column="money" property="money">result>
<association property="user" javaType="user" column="uid" select="com.lagou.mapper.UserMapper.findById">association>
resultMap>
<select id="findAllWithUser" resultMap="orderMap" >
SELECT * FROM orders
select>
3) UserMapper 接口
public interface UserMapper {
public User findById(Integer id);
}
4) UserMapper.xml 映射
<select id="findById" parameterType="int" resultType="user">
SELECT * FROM `user` where id = #{uid}
select>
5)测试代码
@Test
public void testOrderWithUser() throws Exception {
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List<Order> list = orderMapper.findAllWithUser();
for (Order order : list) {
System.out.println(order);
}
}
需求:查询一个用户,与此同时查询出该用户具有的订单。
一对多查询语句
-- 先查询用户
SELECT * FROM `user`;
-- 再根据用户 id 主键,查询订单列表
SELECT * FROM orders where uid = #{用户 id};
a) UserMapper 接口
public interface UserMapper {
public List<User> findAllWithOrder();
}
b) UserMapper.xml 映射
<resultMap id="userMap" type="user">
<id column="id" property="id">id>
<result column="username" property="username">result>
<result column="birthday" property="birthday">result>
<result column="sex" property="sex">result>
<result column="address" property="address">result>
<collection property="orderList" column="id" ofType="order" select="com.lagou.mapper.OrderMapper.findByUid">collection>
resultMap>
<select id="findAllWithOrder" resultMap="userMap">
SELECT * FROM `user`
select>
c) OrderMapper 接口
public interface OrderMapper {
public List<Order> findByUid(Integer uid);
}
d) OrderMapper.xml 映射
<select id="findByUid" parameterType="int" resultType="order">
SELECT * FROM orders where uid = #{uid}
select>
e)测试代码
@Test
public void testUserWithOrder() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findAllWithOrder();
for (User user : list) {
System.out.println(user);
}
}
需求:查询用户同时查询出该用户的所有角色。
多对多查询语句
-- 先查询用户
SELECT * FROM `user`;
-- 再根据用户 id 主键,查询角色列表
SELECT * FROM role r INNER JOIN user_role ur ON r.`id` = ur.`rid`
WHERE ur.`uid` = #{用户 id};
a) UserMapper 接口
public interface UserMapper {
public List<User> findAllWithRole();
}
b) UserMapper.xml 映射
<resultMap id="userAndRoleMap" type="user">
<id column="id" property="id">id>
<result column="username" property="username">result>
<result column="birthday" property="birthday">result>
<result column="sex" property="sex">result>
<result column="adress" property="address">result>
<collection property="roleList" column="id" ofType="role" select="com.lagou.mapper.RoleMapper.findByUid">collection>
resultMap>
<select id="findAllWithRole" resultMap="userAndRoleMap">
SELECT * FROM `user`
select>
c) RoleMapper 接口
public interface RoleMapper {
public List<Role> findByUid(Integer uid);
}
d) RoleMapper.xml 映射
<select id="findByUid" parameterType="int" resultType="role">
SELECT r.id,r.`role_name` roleName,r.`role_desc` roleDesc FROM role r
INNER JOIN user_role ur ON r.`id` = ur.`rid` WHERE ur.`uid` = #{uid}
select>
e)测试代码
@Test
public void testUserWithRole() throws Exception {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findAllWithRole();
for (User user : list) {
System.out.println(user);
}
}