Mybatis基础(基于maven)
概念:是一个持久层的框架
步骤:
创建一个springboot项目:在pom.xml添加Mybatis和MySQL的依赖坐标
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
创建对应表的实体类:实体类的属性要和数据表的字段名一样
public class Emp {
private Integer id;
private String username;
private String password;
private String name;
private Short gender;
private String image;
private Short job;
private LocalDate entrydate;
private Integer deptId;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
创建Mapper【接口】:
需要在接口上添加@Mapper注解
定义一个抽象方法
在抽象方法上面加上对应的注解
在application.properties中加入连接数据库的配置信息【驱动,url、username、password】
@Mapper
public interface DeptMapper {
@Select ("select * from springboot_crud.dept")
List<Dept> findAllDepts();
}
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: 123456
username: root
url: jdbc:mysql://127.0.0.1:3306/springboot_crud
Mybatis操作数据库
增加:使用@insert注解,使用注解一般操作于简单的SQL语句
删除:@delete
修改:@update
查询:@select
如果是模糊查询:concat(开始的符号 , 占位符 , 结束符号 )
如果查询过程中发现实体类的字段名和数据表的字段名不一致,有如下操作:
1、做映射:@Results({ @Result( 表的字段, 实体类的属性)})
2、该配置文件:mybatis.configuration.map-underscore-to-camel-case=true(开启驼峰命名)
SQL注入的问题:#{占位符}---防止SQL注入,${占位符}:SQL注入
xml文件:
1、文件名必须要和接口名相同
2、文件路径要和接口名路径相同
3、xml文件中的namespace要指定接口的全限定类名。标签的id属性要指定方法的名字,且不能重复。
动态SQL:
<if>:判断
<where>:动态去生成where关键字,并且删除多余 or / and
<set>:动态生成set关键字, 删除多余 ","
<foreach>:用于遍历集合
属性:collection:指定遍历的集合
item:遍历时指定变量的名称【可以自定义】
separator:指定分割符号
open:拼接时开始的符号
close:拼接时结束的符号
<sql>:抽取相同的代码,指定id
<include>:引用sql