- MySQL数据库默认使用的是美国的时区,而我们连接的时候用的是中国的北京时间,然后比美国晚上8个小时,所以当我们在连接数据库的时候要设置一下时区为东八区
ServerTimezone=UTC
- 驱动类
- MySQL5.x的版本使用的驱动类是com.mysql.jdbc.Driver
MySQL8.x的版本使用的驱动类是com.mysql.cj.jdbc.Driver
要在pom.xml文件中添加依赖。
数据库驱动依赖<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
数据库连接池依赖
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.9</version></dependency>
添加Mybatis的依赖
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency>
Application启动类添加扫描Dao注解
@MapperScan("com.huojuhao.dao")
application.properties添加配置
#mapper.xml文件地址mybatis.mapper-locations=classpath:mapper/*Mapper.xml#设置别名mybatis.type-aliases-package=com.huojuhao.pojo
mybatis XML配置方式
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!--指定mybatis 使用指定日志--><settings><setting name="logImpl" value="slf4j"/></settings><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/shiro"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><!-- <mapper resource="org/mybatis/example/BlogMapper.xml"/>--><mapper class="com.huojuhao.mapper.UsersMapper"/></mappers></configuration>
xml Mapper文件方式
@Mapperpublic interface StudentDao {//@Select("select * from Student where stu_no=#{id}")public Student getStudentById(int id);}
```java <?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">
多对一结果映射 <br />嵌套结果```xml<association property="dept"><result column="deptname" property="name"/></association>
支持懒加载的分步
嵌套查询
<association property="dept" column="dept_id" select="com.huojuhao.mapper.DeptMapper.findById"/>
一对多结果映射
使用<collection property=”emps” ofType=”Emp/>标签 ofType=>List的泛型


动态sql
标签
if判断标签 代替了 1=1 解决了 多个参数动态拼接 “and” 的问题 类似 switch语句 满足哪个 就执行哪个 都不满足则执行 标签 条件取其一 循环标签 传入集合或数组 <foreach collection=”集合名” item=”单个元素名” separator=”分隔符 一般用’,’ open=”条件前面拼接” close=”条件后面拼接 “> #{item} 用于update语句 前面自动添加set 后面自动去掉最后一个 ‘,’ 在mapper映射文件上下文声明一个变量 定义sql片段 id 唯一标识 配合 refid 需要引用的sql片段id 引用使用 可以抽出公共的mysql语句 重复使用 - 实现模糊查询 like ‘%XX%’
- 1.可以使用mysql的字符串拼接 — 空格拼接 — concat函数拼接
- 2 可以拼接好再传进来
- 3 使用bind再Mapper映射文件上下文声明一个变量
```xml select * form 表名 1=1 <if test=”id!=null and id!=’’> and id=#{id} 同
select * form 表名
条件构造器
模糊查询
排序查询
MyBatis注解
- @TableLogic 添加在实体类的字段上 删除时会执行逻辑删除 设置字段值为1 查询时会自动添加筛选条件 删除字段值 = 0


