創建工程spring-boot-mybatis,創建項目時勾選MyBatis Framework會自動引入MyBatis的Starter
分析Mybatis的Staters啟動器依賴
MyBatis的自動配置類和配置項類都在autoconfigure包下
MyBatis自動配置類依賴了SqlSessionFactory和SqlSessionFactoryBean以及DataSource類,并且啟用了MyBatisProperties類中的屬性作為配置項,并且在DataSourceAutoConfiguration自動配置類和MybatisLanguageDriverAutoConfiguration類生效后才會生效。
MyBatisProperties類源碼中包含了mybatis的配置項
MyBatis的配置前綴都是以mybatis開頭
引入driud
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.8</version></dependency>
Druid數據源配置可以參考 Spring 全家桶之 Spring Boot 2.6.4(四)- Data Access(Part A JDBC)
在resources目錄下放置employee.sql和department.sql文件
SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for employee-- ----------------------------drop TABLE IF EXISTS `employee`;CREATE TABLE `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `lastName` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `gender` int(2) DEFAULT NULL, `d_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for department-- ----------------------------drop TABLE IF EXISTS `department`;CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
entity目錄中創建兩個實體類Employee和Department對應employee表和Department表
@Datapublic class Employee { private Integer id; private String lastName; private String email; private Integer gender; private Integer dId;}
@Datapublic class Department { private Integer id; private String departmentName;}
配置自定義數據源初始化類,初始化數據源
@Configurationpublic class LilithDataSourceInitializer { @Value("classpath:employee.sql") private Resource employee; @Value("classpath:department.sql") private Resource department; @Bean public DataSourceInitializer dataSourceInitializer(final DataSource dataSource){ final DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator()); return initializer; } private DatabasePopulator databasePopulator(){ final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScripts(employee,department); return populator; }}
啟動應用,Spring Boot會自動在數據庫表創建,再次啟動之前如果不想初始化數據可以將@Configuration注解注釋掉
創建DepartmentMapper接口,使用注解標注增刪改查的SQL語句
@Mapperpublic interface DepartmentMapper { @select("select * FROM department WHERE id = #{id}") Department selectOneById(Integer id); @delete("delete FROM department WHERE id = #{id}") void deleteOneById(Integer id); @insert("insert INTO department (department_name) VALUES (#{departmentName})") void insert(Department department); @update("update department SET department_name = #{departmentName} where id = #{departmentId}") void update(Department department);}
創建DepartmentMapperTest測試類,測試DepartmentMapper中的增刪改查方法
@SpringBootTestpublic class DepartmentMapperTest { @Resource private DepartmentMapper departmentMapper; @Test public void selectOneById() { Department department = departmentMapper.selectOneById(1); System.out.println(department); } @Test public void insert() { Department department = new Department(); department.setDepartmentName("Avengers"); departmentMapper.insert(department); }}
測試insert方法
測試selectOneById方法
修改Department表departmentName為下劃線形式department_name;再次執行selectOneById方法
查詢到DepartmentName屬性為空,這時可以在yml配置文件中開啟駝峰命名轉換
mybatis: configuration: map-underscore-to-camel-case: true
再次查詢既可以查詢到指定的是數據
也可以使用配置類來開啟駝峰命名轉換,MyBatisAutoConfuguration中包含了configurationCustomizers屬性,這是一個List列表,包含了所有的自定義配置
而ConfigurationCustomizer接口中有一個customize方法,該方法傳入Configuration自定義配置
Configuration類中的屬性就是可以自定義的配置
在config包下新建LilithMyBatisConfig配置類,新增一個configurationCustomizer方法,既往容器中注入ConfigurationCustomizer設置了屬性的實現類
@Configurationpublic class LilithMyBatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ return configuration -> configuration.setMapUnderscoreToCamelCase(true); }}
這里使用lambda表達式實現了ConfigurationCustomizer接口中的customize方法
將yml文件中的駝峰命名轉換注釋,重新執行selectOneById方法
可以成功查詢出數據。
@Mapper注解是自動配置的關鍵,標記當前類為容器的一個組件,缺少@Mapper注解將無法啟動。
當Mapper接口非常多是,給每一個Mapper接口增加@Mapper注解非常麻煩,可以在主啟動類上使用@MapperScan注解,掃描所有的Mapper接口
創建Mapper接口EmployeeMapper,需要說明的是無論是注解還是配置文件方式使用MyBatis,@Mapper注解或者@MapperScan注解都是必不可少的。
@Mapperpublic interface EmployeeMapper { void insert(Employee employee); Employee selectOneById(Integer id);}
在resources目錄下創建mappers文件夾,新增EmployeeMapper.xml文件,增加Mapper接口中selectOneById方法和insert方法對應的SQL語句
<?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.lilith.mybatis.mapper.EmployeeMapper"> <select resultType="com.lilith.mybatis.entity.Employee"> select * from employee where id = #{id} </select> <insert useGeneratedKeys="true" keyProperty="id" keyColumn="id"> insert INTO employee (last_name, email, gender, d_id) VALUES (#{lastName}, #{email}, #{gender},#{dId}) </insert> </mapper>
yml中增加mybatis配置
mybatis: # 全局配置文件的位置 config-location: classpath:mybatis-config.xml mapper-locations: classpath:mappers/*.xml configuration: map-underscore-to-camel-case: true
書寫測試類
@SpringBootTestpublic class EmployeeMapperTest { @Resource private EmployeeMapper employeeMapper; @Test public void insert() { Employee employee = new Employee(); employee.setLastName("Thanos"); employee.setEmail("thanos@gmail.com"); employee.setGender(1); employee.setDId(1); employeeMapper.insert(employee); } @Test public void selectOneById() { Employee employee = employeeMapper.selectOneById(1); System.out.println(employee); }}
執行插入方法
錯誤提示config-location和configuration不能同時寫在yml文件中; 在resources目錄下新建MyBatis全局配置文件,把configuration配置到mybatis-config.xml全局配置文件中
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings></configuration>
再次執行測試
控制臺顯示有1行成功更新,數據被成功插入到輸入句酷表中
執行selectOneById方法
成功查詢出insert方法插入的數據
本文由 貴州做網站公司 整理發布,部分圖文來源于互聯網,如有侵權,請聯系我們刪除,謝謝!
網絡推廣與網站優化公司(網絡優化與推廣專家)作為數字營銷領域的核心服務提供方,其價值在于通過技術手段與策略規劃幫助企業提升線上曝光度、用戶轉化率及品牌影響力。這...
在當今數字化時代,公司網站已成為企業展示形象、傳遞信息和開展業務的重要平臺。然而,對于許多公司來說,網站建設的價格是一個關鍵考量因素。本文將圍繞“公司網站建設價...
在當今的數字化時代,企業網站已成為企業展示形象、吸引客戶和開展業務的重要平臺。然而,對于許多中小企業來說,高昂的網站建設費用可能會成為其發展的瓶頸。幸運的是,隨...
cdp化妝品是什么牌子?CDP化妝品的全稱是cle de peau beauty,也可以稱為CPB。中文翻譯是肌膚的關鍵,屬于資生堂頂級品牌。1997年正式上市,2001年進入中國市場。品牌在全球20多個國家和地區設立了300多個形象專柜。CPB系列產品為各類肌膚提供最基本的護理產品,同時也為個別肌膚提供特殊護理產品,讓肌膚展現自然優雅的美。CDP是什么意思?日內反向操作技術指標,又稱逆勢操作指數...
pv值、sp值、op值是甚么意思?PV的英文全稱是process value。SP的英文全名為set point。OP的英文全名是output value??刂破鱬v和sp是什么?1. PV的英文全稱為“過程值”,是指當前的過程測量值。2. SP的英文全稱為“set point”,是指PID控制的設定值。pv和sv是什么意思?元件的設定值(通常我們設定溫度、壓力、流量、電壓、電流等),SV有時寫為...
北京國家會議中心在什么地方?公交路線:地鐵4號線大興線地鐵2號線地鐵8號線,全程約23.4公里。1.從公益西橋乘坐地鐵4號線大興線,經過6站到達宣武門站。2.乘坐地鐵2號線,經過7站,到達鼓樓街站。3.乘坐地鐵8號線,經過4站,到達奧林匹克公園站(E出口)。4.步行約440米至國家會議中心。北京國家會議中心在什么地方?我想參加CP05伴侶節…但是不知道國家會議中心在哪里?地鐵可以直達嗎?我住的地方...