1.mybatis是什么
MyBatis 是一款優秀的持久層框架,它支持自定義 SQL、存儲過程以及高級映射。MyBatis 免除了幾乎所有的 JDBC 代碼以及設置參數和獲取結果集的工作。MyBatis 可以通過簡單的 XML 或注解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)為數據庫中的記錄。
2.整合
兩種方式:
- 新建一個mybaits-config.xml文件,內容配置其中
- 在springboot核心配置文件application.yaml中,配置mybatis內容(這邊只展示第二種)
2.0 前期工作:保證可以連接上數據庫
導入依賴:
<!--數據庫啟動器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: xxx
url: jdbc:mysql://localhost:3306/mybatis
springboot中默認使用hikari連接池,號稱最快的連接池。連接池還有DBCP,c3p0,druid…
2.1 導入依賴
<!--引入 mybatis-spring-boot-starter 的依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
2.2 創建包和類
mapper層:
@Mapper
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
mapper層對應的xm文件:
<?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">
<mapper namespace="com.example.mapper.EmployeeMapper">
<select id="getEmpById" resultType="com.example.entity.Employee">
select * from employee where id = #{id}
</select>
</mapper>
2.3 在application.yaml配置mybatis
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml # 找到mapper層對應的xml文件
config-location: mybatis-config.xml # mybatis配置文件,resource目錄下
mybaits的屬性設置參考文檔:https://mybatis.net.cn/configuration.html#settings
3.使用注解版mybaits
在mapper接口的方法上,使用注解增刪改查@Update()、 @Insert()、 @Select()、@Delete()
@Insert("insert into employee (name,age,position) values(#{name},{age},#{position})")
void insert(Employee employee);
@Select("select * from employee where id = #{id}")
void selectById(Integerid);
4.實戰過程
- 引入mybatis-spring-boot-start
- 配置application.yaml中,指定mapper-locations位置
- 編寫mapper接口并標注@Mapper注解
- 簡單方法直接使用注解
- 復雜方法編寫在mapper.xml進行綁定映射
- @MapperScan(“com.lmh.mapper”)簡化,該目錄下的mapper接口就可不添加@Mapper注解
到此這篇關于springboot整合mybatis流程詳解的文章就介紹到這了,更多相關springboot mybatis內容請搜索html5模板網以前的文章希望大家以后多多支持html5模板網!