Mybatis二

编码格式错误

控制台错误提示:
MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
解决方案,在pom文件中加入配置

copy
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>

分页插件

现在我们要学习使用一个常用的mybatis的插件 --> 分页插件-PageHelper
使用流程

使用流程

引入依赖

copy
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.0</version> </dependency>

全局配置文件使用插件

copy
<!-- 插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"/> </plugins>

【在执行查询前设置】
// 参数1: 当前页
// 参数2: 每页大小
PageHelper.startPage(2,2);

ORM映射

2.1 MyBatis自动ORM失效

MyBatis只能自动维护库表”列名“与”属性名“相同时的一一对应关系,二者不同时,无法自动ORM

2.2方案一:列的别名

在SQL中使用 as 为查询字段添加列别名,以匹配属性名。

方案二:结果映射(ResultMap - 查询结果的封装规则)

通过< resultMap id="" type="" >映射,匹配列名与属性名。

copy
<mapper namespace="com.qf.mapper.UserMapper"> <!--定义resultMap标签--> <resultMap id="findUserByIdResultMap" type="user"> <!--关联主键与列名--> <id property="idd" column="id" /> </resultMap> <!--使用resultMap作为ORM映射依据--> <select id="findUserById" resultMap="findUserByIdResultMap"> select id,username,password,phone,create_time,sex,money from tb_user where id = #{id} </select> </mapper>

多表联查

3.1 OneToOne

案例:订单 ---> 用户 (1 VS 1) 一个订单只会属于一个人

因为在创建数据库的表,用户表中没有订单的信息,订单表中没有用户的信息,因此我们需要重新创建扩展类XXXXOV,包含以上全部属性,扩展类可以继承以上一个实体类,私有化创建另一个全局成员变量

XXX.xml(扩展类的映射文件)

copy
<resultMap id=""orderWithUserResultMap" type=""OrderVO"> <!-- 封装查询主体XXX: --> <id column="oid" property="oid"/> <result column="xxxx" property="xxxx"/> 。....................... <!-- 一对一映射,需要封装关联的XXX对象 --> <!-- 一对一映射,需要特殊标签 association--> <!-- property="user" 是OrderVO类中的属性,javaType是user属性的类型 --> <association property=""user" javaType="User"> <!-- 下面正常的列和属性 一一映射 -- <id column="id" property="id"/> <result column="username" property="username"/> <result column="xxxx" property="xxxx"/> ................... </association> </resultMap> <!-- 多表联查,直接返回resultType无法封装关联的那个对象,就使用使用resultMap手动映射 --> <select id=""findXXX" resultMap="orderWithUserResultMap"> SELECT *************** </select>

OneToMore

与上面OneToOne不同的是<association property="xxx" javaType="Xxxxx">替换为<collection property="orderList" ofType="com.qf.model.Order">

关联查询总结

正常封装使用resultMap
一对一封装使用association
一对多封装使用collection

动态sql

常见的动态SQL语法

posted @   卡卡罗特kk  阅读(6)  评论(0编辑  收藏  举报
相关博文:
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
展开