MyBatis 时一款优秀的持久层框架,用于简化JDBC的开发
The MyBatis Blog
目录
- MyBatis入门
- Mybatis基础CRUD
- Mybatis动态SQL
Mybatis入门
-
快速入门
-
JDBC介绍
-
数据库连接池
-
lombok
-
准备工作(创建springboot工程,数据库表user,实体类User)
-
引入Mybatis的相关依赖,配置Mybatis(数据库的连接信息)
-
编写SQL语句
-
数据库表中的字段和实例用的属性名一一对应
-
配置Mybatis的依赖
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=1234
- 编写SQL语句
@Mapper
public interface UserMapper {@Select("select * from user")public List<User> list();
}
- 编写测试
@SpringBootTest
class SpringbootMybatisQuickstart1ApplicationTests {@Autowiredprivate UserMapper userMapper;@Testpublic void test1(){List<User> userList = userMapper.list();userList.stream().forEach(user -> {System.out.println(user);});}
}
注:要在主入口上面添加@MapperScan("org.mybatis.mapper")
,告诉bean对象在哪个文件夹下
@SpringBootApplication
@MapperScan("org.mybatis.mapper")
public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } }
JDBC(Java DataBase Connectivity)介绍
本质
- sun 公司官方定义的一套操作所有关系型数据库的规范,即接口。
- 各个数据库厂商去实现这套接口,提供数据库驱动 jar 包。
- 我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动 jar 包中的实现类。
数据库连接池
- 数据库连接池是个容器,负责分配、管理数据库连接 (Connection)
- 它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个
- 释放空闲时间超过最大空闲时间的连接,来避免因为没有释放连接而引起的数据库连接遗漏
优势
- 资源重用
- 提升系统响应速度
- 避免数据库连接遗漏
注:springboot默认的数据库连接池 Hikari
小结:
- 是一个容器,负责分配、管理数据库连接 (Connection)
- 优势:资源复用、提升系统响应速度
- 接口:DataSource
- 产品:C3P0、DBCP、Druid、Hikari
lombok
- 是一个实用的Java类库,能通过注解的形式自动生成构造器,getter/setter, equals , hashcode,toString 等方法,并可以自动化生成日志变量,简化java开发,提高效率
注解 | 作用 |
---|---|
@Getter/@Setter | 为所有的属性提供 get/set 方法 |
@ToString | 会给类自动生成易阅读的 toString 方法 |
@EqualsAndHashCode | 根据类所拥有的非静态字段自动重写 equals 方法和 hashCode 方法 |
@Data | 提供了更综合的生成代码功能(@Getter + @Setter + @ToString + @EqualsAndHashCode) |
@NoArgsConstructor | 为实体类生成无参的构造器方法 |
@AllArgsConstructor | 为实体类生成除了 static 修饰的字段之外带有各参数的构造器方法 |
lombok的依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId>
</dependency>
Mybatis基础操作
准备
- 准备数据库表
- 创建一个新的springboot,选择引入对应的起步依赖(mybatis,mysql)
- application.properties 中引入数据库连接信息
- 创建对应的实体类 Emp(实体类属性采用驼峰命名)
- 准备Mapper接口EmpMapper
注:
- Java中的
LocalDateTime
--> datetime - Java中的
LocalDate
--> date - Java中的属性采用大驼峰命名,数据库中采用下划线命名
删除
@Mapper
public interface UserMapper {@delete("delete from emp where id = #{id}")public int delete(Integer id);
}
@SpringBootTest
class SpringbootMybatisQuickstart1ApplicationTests {@Autowiredprivate UserMapper userMapper;@Testpublic void test(){int delete = userMapper.delete(12);sout(delete);}
}
注:如果mapper接口方法形参只有一个普通连续的参数,#{} 里面的属性名可以随便写
- #{} 生成预编译SQL,会自动设置参数值
- 预编译SQL
- 性能更高
- 更安全(防止SQL注入)
- ${}
- 拼接SQL,存在SQL注入问题
新增
@Mapper
public interface UserMapper {@delete("delete from emp where id = #{id}")public int delete(Integer id);@Insert("... values(#{name})")public void insert(Emp emp);
}
注:name是emp中的属性名
主键返回:在数据添加成功后,许哟啊获取插入数据库数据的主键
实现
@Options(useGeneratedKeys = true,keyProperty = "id")@Insert("... values(#{name})")public void insert(Emp emp);
会将主键封装到emp实类的 id 属性中
更新
@Mapper
public interface UserMapper {@delete("delete from emp where id = #{id}")public int delete(Integer id);@Insert("... values(#{name})")public void insert(Emp emp);@Update("...")public void update(Emp emp);}
查询
@Mapper
public interface UserMapper {@Select("select * from user")public Emp list();
}
-
数据封装
- 实体类属性名 和 数据库表查询返回的字段名一致,mybatis会自动封装
- 如果实体类属性 和 数据库表查询返回的字段名不一致,不能自动封装
-
解决方案
- 起别名
- 通过 @Results注解手动映射封装
- 开启mybatis的驼峰命名自动映射的开关
@Mapper
public interface UserMapper {@Select("select user_name userName from user")public Emp list();
}
@Mapper
public interface UserMapper {@Result({@Resule(coulmn = "user_name", property = "userName")@Resule(coulmn = "xxx", property = "xxx")})@Select("select user_name UserName from user")public Emp list();
}
条件查询 中使用concat
的案例
@Select("select * from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc")
public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
XML映射文件
- 规范
- XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下
- XML映射文件的namespace属性为Mapper接口全限定名一致
- XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致
- 复杂的MySQL,推荐使用XML
注:到官网找到配置SQL语句的XML的约束
- 插件介绍
- MybatisX是一款基于IDEA的快速开发Mybatis的插件,为效率而生
动态SQL
例子:
<select id="list" resultType="com.itheima.pojo.Emp">select id, username, password, name, gender, image, job,entrydate, dept_id, create_time, update_time from empwhere<if test="name != null">name like concat('%',#{name},'%')</if><if test="gender != null">and gender = #{gender}</if><if test="begin != null and end != null">and entrydate between #{begin} and #{end}</if>order by update_time desc
</select>
- <where>
- 动态生成where (如果if 里面都不成立,就不会生成where)
- 自动去除多余的
and
,or
- <set>
- 动态生成 set
- 自动去除
,
- 用于
update
语句中
- <if>
- 用于判断条件是否成立,使用test属性进行判断,如果条件为true,则拼接SQL
- <foreach>
- collection:遍历的集合
- item:遍历出来的元素
- open:遍历开始前拼接的SQL片段
- close:遍历结束后拼接的SQL片段
- <sql><include>
- 提高SQL的复用性
- sql --> 需要一个id
- include --> refid 指定引入的sql