2 - Mybatis 常用

2 MyBatis 常用

2.1 ResultMap

如果实体的属性名与表中字段名不一致,可以使用ResutlMap实现手动封装到实体类中

resultType : 如果实体的属性名与表中字段名一致,将查询结果自动封装到实体类中

<!--id : 标签的唯一标识
    type: 封装后实体类型-->
<resultMap id="userResultMap" type="com.dy.domain.User">
    <!--手动配置映射关系-->
    <!--id: 用来配置主键-->
    <id property="id" column="id"></id>
    <!-- result: 表中普通字段的封装-->
    <result property="username" column="username"></result>
    <result property="birthday" column="birthday"></result>
    <result property="sex" column="sex"></result>
    <result property="address" column="address"></result>
</resultMap>
2.2 多条件查询
@Param()
List<User> findByIdAndUsername2(@Param("id") int id, @Param("username") String username);
<select id="findByIdAndUsername2" resultMap="userResultMap" >
    select * from user where id = #{id} and username = #{username}
</select>
使用pojo对象传递参数
List<User> findByIdAndUsername3(User user);
<select id="findByIdAndUsername3" resultMap="userResultMap" parameterType="com.dy.domain.User">
    select * from user where id = #{id} and username = #{usernameabc}
</select>
2.3 模糊查询
#{} (推荐使用)
List<User> findByUsername(String username);
<select id="findByUsername" resultMap="userResultMap" parameterType="string">
    <!-- #{}在mybatis中是占位符,引用参数值的时候会自动添加单引号 -->
    select * from user where username like #{username}
</select>
@Test
public void test6() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // 当前返回的 其实是基于UserMapper所产生的代理对象:底层:JDK动态代理 实际类型:proxy
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> users = mapper.findByUsername("%子慕%");
    for (User user : users) {
        System.out.println(user);
    }
    sqlSession.commit();
    sqlSession.close();
}
#{} 和 ${}

#{}:表示一个占位符号

  • 通过 #{} 可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入。
  • #{} 可以接收简单类型值或pojo属性值。
  • 如果parameterType传输单个简单类型值, #{} 括号中名称随便写。

${}:表示拼接sql串

  • 通过 ${} 可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换,会出现sql注入
    问题。
  • ${} 可以接收简单类型值或pojo属性值。
  • 如果parameterType传输单个简单类型值, ${} 括号中只能是value。
2.4 返回主键(主键回填)
<!--添加用户:获取返回主键:方式一-->
<!--
        useGeneratedKeys: 声明返回主键
        keyProperty:把返回主键的值,封装到实体中的那个属性上
    -->
<insert id="saveUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
    insert into user(username, birthday, sex, address)
    values (#{username}, #{birthday}, #{sex}, #{address})
</insert>


<!--添加用户:获取返回主键:方式二-->
<insert id="saveUser2" parameterType="user">
    <!--
            selectKey : 适用范围更广,支持所有类型的数据库
                order="AFTER"  : 设置在sql语句执行前(后),执行此语句
                keyColumn="id" : 指定主键对应列名
                keyProperty="id":把返回主键的值,封装到实体中的那个属性上
                 resultType="int":指定主键类型
        -->
    <selectKey order="AFTER" keyColumn="id" keyProperty="id" resultType="int">
        SELECT LAST_INSERT_ID();
    </selectKey>
    insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
2.5 动态sql
if

根据id和username查询,但是不确定两个都有值。

<!-- 动态sql之if : 多条件查询-->
<select id="findByIdAndUsernameIf" parameterType="user" resultType="com.dy.domain.User">
    select * from user
    <!-- test里面写的就是表达式
        <where>: 相当于where 1= 1,但是如果没有条件的话,不会拼接上where关键字
    -->
    <where>
        <if test="id != null">
            and id = #{id}
        </if>
        <if test="username !=null">
            and username = #{username}
        </if>
    </where>
</select>
set

动态更新user表数据,如果该属性有值就更新,没有值不做处理

<!--动态sql之set : 动态更新-->
<update id="updateIf" parameterType="user">
    update user
    <!--<set> : 在更新的时候,会自动添加set关键字,还会去掉最后一个条件的逗号 -->
    <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

主要是用来做数据的循环遍历,类似 where id in (1,2,3) 传入的参数部分必须依靠foreach遍历才能实现。

如果查询条件为普通类型 List集合,collection属性值为:collection 或者 list

如果查询条件为普通类型 Array数组,collection属性值为:array

<!--动态sql的foreach标签:多值查询:根据多个id值查询用户-->
<select id="findByList" parameterType="list" resultType="user">
    <include refid="selectUser"/>
    <where>
        <!--
            collection : 代表要遍历的集合元素,通常写collection或者list
            open : 代表语句的开始部分
            close : 代表语句的结束部分
            item : 代表遍历结合中的每个元素,生成的变量名
            separator: 分隔符
         -->
        <foreach collection="collection" open="id in (" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

<!--动态sql的foreach标签:多值查询:根据多个id值查询用户-->
<select id="findByArray" parameterType="int" resultType="user">
    <include refid="selectUser"/>
    <where>
        <!--
                collection : 代表要遍历的集合元素,通常写collection或者list
                open : 代表语句的开始部分
                close : 代表语句的结束部分
                item : 代表遍历结合中的每个元素,生成的变量名
                separator: 分隔符
             -->
        <foreach collection="array" open="id in (" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>
sql片段

映射文件中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的

<!--抽取的sql片段-->
<sql id="selectUser">
	SELECT * FROM `user`
</sql>
<select id="findByList" parameterType="list" resultType="user" >
    <!--引入sql片段-->
    <include refid="selectUser"></include>
    	<where>
            <foreach collection="collection" open="id in(" close=")" item="id"
            separator=",">
            #{id}
            </foreach>
    	</where>
</select>
2.6 PageHelper
  1. 导入依赖
  2. 核心配置文件进行配置
  3. 使用
<!-- 分页助手 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>3.7.5</version>
</dependency>
<dependency>
    <groupId>com.github.jsqlparser</groupId>
    <artifactId>jsqlparser</artifactId>
    <version>0.9.1</version>
</dependency>
<plugins>
    <plugin interceptor="com.github.pagehelper.PageHelper">
        <!--dialect: 指定方言 limit-->
        <property name="dialect" value="mysql"/>
    </plugin>
</plugins>
@Test
public void test15() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    // 设置分页参数
    // 参数1: 当前页
    // 参数2: 每页显示的条数
    PageHelper.startPage(1,2);
    List<User> users = mapper.findAllResultMap();
    for (User user : users) {
        System.out.println(user);
    }
    // 获取分页相关的其他参数
    PageInfo<User> pageInfo = new PageInfo<User>(users);
    System.out.println("总条数"+ pageInfo.getTotal());
    System.out.println("总页数"+ pageInfo.getPages());
    System.out.println("是否是第一页"+ pageInfo.isIsFirstPage());
    sqlSession.close();
}
2.7 多表查询
1 对 1 association

一个订单只从属于一个用户 查订单的时候把用户信息查出来

Orders实体类

public class Orders {
    private Integer id;
    private String ordertime;
    private Double total;
    private Integer uid;

    // 表示当前订单属于那个用户 association
    private User user;
}

Mapper.xml

<!--一对一关联查询:查询所有订单,与此同时还要查询出每个订单所属的用户信息-->

<resultMap id="orderMap" type="com.dy.domain.Orders">
    <id property="id" column="id"/>
    <result property="ordertime" column="ordertime"/>
    <result property="total" column="total"/>
    <result property="uid" column="uid"/>
    <!--
        association : 在进行一对一关联查询配置时,使用association标签进行关联
            property="user" :要封装实体的属性名
            javaType="com.dy.domain.User" 要封装的实体的属性类型
    -->
    <association property="user" javaType="com.dy.domain.User">
        <id property="id" column="uid"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
    </association>
</resultMap>

<select id="findAllWithUser" resultMap="orderMap">
    SELECT * FROM orders o LEFT JOIN USER u ON o.uid = u.id
</select>
1 对 多 collection

一个用户有多个订单,查用户的时候把他的订单查出来

public class User  implements Serializable {

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    // 表示多方关系:集合 : 代表了当前用户所具有的订单列表 collection
    private List<Orders> ordersList;

    // 表示多方关系:集合 : 代表了当前用户所具有的角色列表 collection
    private List<Role> roleList;
}
<select id="findAllWithOrder"  resultMap="userMap">
   SELECT u.*,o.id oid,o.ordertime,o.total,o.uid FROM orders o RIGHT JOIN USER u ON o.uid = u.id
</select>

<!--一对多关联查询:查询所有的用户,同时还要查询出每个用户所关联的订单信息-->

<resultMap id="userMap" type="com.dy.domain.User">
    <id property="id" column="id"></id>
    <result property="username" column="username"></result>
    <result property="birthday" column="birthday"></result>
    <result property="sex" column="sex"></result>
    <result property="address" column="address"></result>
    <!--
            collection : 一对多使用collection标签进行关联
        -->
    <collection property="ordersList" ofType="com.dy.domain.Orders">
        <id property="id" column="oid"></id>
        <result property="ordertime" column="ordertime"/>
        <result property="total" column="total"/>
        <result property="uid" column="uid"/>
    </collection>

</resultMap>
多 对 多

一个用户有多个角色,一个角色被多个用户使用

其实是一对多的变种

<!--多对多关联查询:查询所有的用户,同时还要查询出每个用户所关联的角色信息-->
<resultMap id="userRoleMap" type="user">
    <id property="id" column="id"/>
    <result property="username" column="username"></result>
    <result property="birthday" column="birthday"></result>
    <result property="sex" column="sex"></result>
    <result property="address" column="address"></result>

    <collection property="roleList" ofType="role">
        <id column="rid" property="id"></id>
        <result column="rolename" property="rolename"></result>
        <result column="roleDesc" property="roleDesc"></result>
    </collection>
</resultMap>

<select id="findAllWithRole" resultMap="userRoleMap">
    SELECT u.*,r.id rid,r.rolename,r.roleDesc FROM USER u LEFT JOIN sys_user_role ur ON ur.userid = u.id
    LEFT JOIN sys_role r ON ur.roleid = r.id
</select>
2.8 嵌套查询

将原来多表查询中的联合查询拆成单个查询 (简化多表查询操作,但是浪费性能

1 对 1 association

查询一个订单,与此同时查询出该订单所属的用户

SELECT * FROM orders o LEFT JOIN USER u ON o.uid = u.id

-- 先查询订单
SELECT * FROM orders;
-- 再根据订单uid外键,查询用户
SELECT * FROM `user` WHERE id = #{订单的uid};

接口需要2个

/*
	一对一嵌套查询:查询所有订单,与此同时还要查询出每个订单所属的用户信息
*/
List<Orders> findAllWithUser2();

/*
	根据uid查询对应订单
*/
List<Orders> findByUid(Integer uid);

映射文件

<resultMap id="orderMap2" type="com.dy.domain.Orders">
    <id property="id" column="id"/>
    <result property="ordertime" column="ordertime"/>
    <result property="total" column="total"/>
    <result property="uid" column="uid"/>
    <!--问题:1.怎么去执行第二条sql , 2.如何执行第二条sql的时候,把uid作为参数进行传递-->
    <association property="user" javaType="com.dy.domain.User"
                 select="com.dy.mapper.UserMapper.findById" column="uid" fetchType="eager"/>
</resultMap>

<!--一对一嵌套查询-->
<select id="findAllWithUser2" resultMap="orderMap2">
    SELECT *
    FROM orders
</select>

<select id="findByUid" parameterType="int" resultType="com.dy.domain.Orders">
    SELECT *
    FROM orders
    WHERE uid = #{uid}
</select>
1 对 多 collection

查询所有用户,与此同时查询出该用户具有的订单

-- 先查询用户
SELECT * FROM `user`;
-- 再根据用户id主键,查询订单列表
SELECT * FROM orders where uid = #{用户id};

接口

/*
	根据id查询用户
*/
User findById(Integer id);
/*
	一对多嵌套查询:查询所有的用户,同时还要查询出每个用户所关联的订单信息
*/
List<User> findAllWithOrder2();

映射文件xml

<!--一对多嵌套查询:查询所有的用户,同时还要查询出每个用户所关联的订单信息-->
<resultMap id="userOrderMap" type="com.dy.domain.User">
    <id property="id" column="id"/>
    <result property="username" column="username"></result>
    <result property="birthday" column="birthday"></result>
    <result property="sex" column="sex"></result>
    <result property="address" column="address"></result>
    <!--fetchType="lazy" : 延迟加载策略
            fetchType="eager": 立即加载策略
        -->
    <collection property="ordersList" ofType="com.dy.domain.Orders" column="id"
                select="com.dy.mapper.OrderMapper.findByUid" ></collection>
</resultMap>

<select id="findAllWithOrder2" resultMap="userOrderMap">
    SELECT * FROM USER
</select>

<!--
	根据id查询用户
 	useCache="true" 代表当前这个statement是使用二级缓存
 -->
<select id="findById" resultType="com.dy.domain.User" parameterType="int" useCache="true">
    SELECT * FROM user WHERE id = #{id}
</select>
多 对 多

一个用户有多个角色,一个角色被多个用户使用。类似一对多

/*
	多对多嵌套查询:查询所有的用户,同时还要查询出每个用户所关联的角色信息
*/
List<User> findAllWithRole2();

/*
	根据用户id查询对应角色
*/
List<Role> findByUid(Integer uid);
<resultMap id="userRoleMap2" type="com.dy.domain.User">
    <id property="id" column="id"/>
    <result property="username" column="username"></result>
    <result property="birthday" column="birthday"></result>
    <result property="sex" column="sex"></result>
    <result property="address" column="address"></result>

    <collection property="roleList" ofType="com.dy.domain.Role" column="id" select="com.lagou.mapper.RoleMapper.findByUid"></collection>
</resultMap>

<!--多对多嵌套查询:查询所有的用户,同时还要查询出每个用户所关联的角色信息-->
<select id="findAllWithRole2" resultMap="userRoleMap2">
    SELECT * FROM USER
</select>

<select id="findByUid" resultType="com.dy.domain.Role" parameterType="int">
    SELECT * FROM sys_role r INNER JOIN sys_user_role ur ON ur.roleid = r.id
    WHERE ur.userid = #{uid}
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值