Spring配置文件和mybatis詳解
1.配置文件
1.1 概述
計算機配置文件:用于存儲系統(tǒng)、應用程序的設置信息,通常以文本或結(jié)構(gòu)化數(shù)據(jù)格式(如JSON、XML、INI等)保存。其核心功能包括但不限于:
- 參數(shù)定制:允許用戶或管理員調(diào)整軟件或硬件的運行參數(shù)
- 環(huán)境適配:根據(jù)不同設備或場景加載特定配置(如開發(fā)/生產(chǎn)環(huán)境)
- 持久化存儲:確保重啟后設置仍生效
SpringBoot配置文件:SpringBoot支持多種類型的配置文件,常見的格式包括properties、yaml和yml,主要用于集中管理應用程序的各種配置參數(shù),簡化部署和開發(fā)過程中的環(huán)境切換
- YAML和YML本質(zhì)上是相同的文件格式,只是文件擴展名的不同,兩者在功能和使用上沒有區(qū)別
1.2 properties
- properties配置文件是最早期的配置?件格式,也是創(chuàng)建SpringBoot項?默認的配置?件
- 采用常見的鍵值對格式(key=value)
- 支持
#開頭的注釋
#應用程序名稱 spring.application.name=configuration #應用程序端口號 server.port=8080 #數(shù)據(jù)庫連接信息 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=root
1.3 yml
- 采用鍵值對格式(key: value),冒號后必須有空格
- 數(shù)據(jù)序列化格式,通過縮進表示層級關系
- 支持
#開頭的注釋
spring:
application:
#應用程序名稱
name: configuration
#數(shù)據(jù)庫連接信息
datasource:
url: jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false
username: root
password: root
#應用程序端口號
server:
port: 80801.4 優(yōu)缺點對比
properties
- 優(yōu)點:
- 語法簡單直觀,采用key=value形式,適合初學者快速上手
- 與Java生態(tài)兼容性極強
- 缺點:
- 缺乏層次結(jié)構(gòu),復雜配置時容易冗余。上述配置數(shù)據(jù)庫連接信息時spring.datasource前綴冗余
- 不支持數(shù)據(jù)類型定義,所有值均為字符串,需手動轉(zhuǎn)換
yml
- 優(yōu)點:
- 層次化結(jié)構(gòu)清晰,通過縮進表示層級,適合復雜配置場景
- 支持數(shù)據(jù)類型(如布爾值、數(shù)字),減少手動類型轉(zhuǎn)換
- 缺點:
- 格式錯誤易導致解析失敗(容易忽略冒號后空格)
- 部分舊版工具鏈兼容性較差,需額外依賴解析庫
注:SpringBoot同時支持兩種格式,混合使用時若key重復,properties優(yōu)先級高于yml
1.5 @Value注解
作用:是Spring框架提供了一個@Value注解(org.springframework.beans.factory.annotation.Value),用于將外部配置文件中的值注入到Spring管理的Bean中
示例:(properties和yml的讀取方式相同)
package org.example.configuration.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Value("${spring.application.name}")
private String applicationName;
@Value("${server.port}")
private Integer port;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
public void print() {
System.out.println("applicationName=" + applicationName);
System.out.println("port=" + port);
System.out.println("url=" + url);
System.out.println("username=" + username);
System.out.println("password=" + password);
}
}
package org.example.configuration;
import org.example.configuration.config.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class ConfigurationApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ConfigurationApplication.class, args);
Config config = context.getBean(Config.class);
config.print();
}
}運行結(jié)果:
applicationName=configuration
port=8080
url=jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false
username=root
password=root
2.mybatis
2.1 概述
MyBatis是一款優(yōu)秀的持久層框架,支持自定義 SQL、存儲過程、高級映射以及多種配置方式。它消除了幾乎所有的JDBC代碼和參數(shù)的手動設置以及結(jié)果集的檢索
- 支持存儲過程:指的是數(shù)據(jù)庫管理系統(tǒng)(DBMS)允許用戶創(chuàng)建、存儲和執(zhí)行存儲過程的能力。存儲過程是一組預編譯的SQL語句,存儲在數(shù)據(jù)庫中,可以被應用程序調(diào)用執(zhí)行
- 支持高級映射:指通過配置或注解實現(xiàn)復雜SQL查詢結(jié)果與Java對象之間的靈活轉(zhuǎn)換。其核心目標是簡化數(shù)據(jù)庫關聯(lián)操作,提升開發(fā)效率
- 支持多種配置方式:mybatis支持注解和xml兩種配置方式

2.2 前置操作
引入依賴:Spring Web,Mybatis Framework,MySQL Driver,Lombok

在application.properties/yml中添加數(shù)據(jù)庫連接信息:
#應用程序名稱 spring.application.name=configuration #應用程序端口號 server.port=8080 #數(shù)據(jù)庫連接信息 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=root #自動駝峰轉(zhuǎn)換 mybatis.configuration.map-underscore-to-camel-case=true
spring:
application:
#應用程序名稱
name: configuration
#數(shù)據(jù)庫連接信息
datasource:
url: jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false
username: root
password: root
#應用程序端口號
server:
port: 8080
mybatis:
configuration:
map-underscore-to-camel-case: true #自動駝峰轉(zhuǎn)換SQL命名規(guī)范:采用下劃線分隔單詞(如order_detail)Java命名規(guī)范:大駝峰/小駝峰
2.3 注解
2.3.1 配置
- 1.創(chuàng)建一個接口,并使用 @Mapper注解 修飾
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BlogMapper {
//其他代碼
}@Mapper注解:允許開發(fā)者直接在接口方法上通過注解配置SQL語句,無需編寫XML映射文件。適用于簡單SQL場景,能顯著減少配置量
- 2.初始化數(shù)據(jù)
create table blog (id int primary key auto_increment,name varchar(128),age int); insert into blog values (null,'劉備',30),(null,'關羽',28),(null,'張飛',25);
- 3.創(chuàng)建對應實體類
import lombok.Data;
@Data
public class PersonInfo {
private Integer id;
private String name;
private Integer age;
public PersonInfo(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public PersonInfo() {
}
}2.3.2 CRUD
import com.example.spring_mybatis.model.PersonInfo;
import org.apache.ibatis.annotations.*;
@Mapper
public interface BlogMapper {
@Select("select * from blog")
List<PersonInfo> getPersonInfoAll();
@Insert("insert into blog values (#{id},#{name},#{age})")
Integer addPerson(PersonInfo person);
@Update("update blog set name = #{name},age = #{age} where id = #{id}")
Integer updatePerson(PersonInfo personInfo);
@Delete("delete from blog where id = #{id}")
Integer deletePerson(Integer id);
}按住alt+insert,可在test目錄下生成以上方法的測試方法
import com.example.spring_mybatis.model.PersonInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
@Slf4j
class BlogMapperTest {
private final BlogMapper blogMapper;
@Autowired
public BlogMapperTest(BlogMapper blogMapper) {
this.blogMapper = blogMapper;
}
@Test
void getPersonInfoAll() {
List<PersonInfo> personInfoAll = blogMapper.getPersonInfoAll();
log.info("查詢成功,personInfoAll:{}",personInfoAll.toString());
//查詢成功,personInfoAll:[PersonInfo(id=1, name=劉備, age=30),
//PersonInfo(id=2, name=關羽, age=28),
//PersonInfo(id=3, name=張飛, age=25)]
}
@Test
void addPerson() {
Integer ret = blogMapper.addPerson(new PersonInfo(null, "趙云", 25));
log.info("添加成功,影響行數(shù):{}",ret.toString());//添加成功,影響行數(shù):1
}
@Test
void updatePerson() {
Integer ret = blogMapper.updatePerson(new PersonInfo(1, "劉備", 35));
log.info("更新成功,影響行數(shù):{}",ret.toString());//更新成功,影響行數(shù):1
}
@Test
void deletePerson() {
Integer ret = blogMapper.deletePerson(4);
log.info("刪除成功,影響行數(shù):{}",ret.toString());//刪除成功,影響行數(shù):1
}
}2.3.3 @Param
作用:用于在Mapper接口方法中為形式參數(shù)指定名稱。當方法有多個參數(shù)時,通過該注解明確SQL中引用的參數(shù)名,避免依賴參數(shù)順序
@Mapper
public interface BlogMapper {
//@Param
@Update("update blog set name = #{name},age = #{age} where id = #{id}")
Integer updatePersonInfo(@Param("id") Integer userId,@Param("name") String userName,@Param("age") Integer userAge);
}@SpringBootTest
@Slf4j
class BlogMapperTest {
private final BlogMapper blogMapper;
@Autowired
public BlogMapperTest(BlogMapper blogMapper) {
this.blogMapper = blogMapper;
}
@Test
void updatePersonInfo() {
Integer ret = blogMapper.updatePersonInfo(1, "劉玄德", 30);
log.info("更新成功,影響行數(shù):{}",ret.toString());//更新成功,影響行數(shù):1
}
}
2.4 xml
2.4.1 配置
- 1.創(chuàng)建一個接口,并使用 @Mapper注解 修飾
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BlogXMLMapper {
//其他代碼
}
- 2.配置mybatis的xml文件路徑
mybatis: mapper-locations: classpath:mybatis/**Mapper.xml #配置mybatis的xml文件路徑 #標識位于resources/mybatis路徑下任何以Mapper結(jié)尾的xml文件為mybatis的配置文件

- 3.在resources/mybatis路徑下創(chuàng)建以Mapper結(jié)尾的xml文件,并添加如下代碼
<?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"> <!--namespace:用于指定該XML文件對應的Java接口或類的全限定名--> <mapper namespace="com.example.spring_mybatis.mapper_blog.BlogXMLMapper"> </mapper>
2.4.2 示例
在接口中聲明方法
import com.example.spring_mybatis.model_blog.PersonInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface BlogXMLMapper {
List<PersonInfo> getPersonInfoAll();
}在對應xml文件中實現(xiàn)接口方法
- id:是MyBatis映射文件中SQL語句的唯一標識符。需與Mapper接口中的方法名一致,保證映射正確
- resultType:指定SQL查詢結(jié)果映射的Java對象類型,需為全限定類名
<mapper namespace="com.example.spring_mybatis.mapper_blog.BlogXMLMapper">
<select id="getPersonInfoAll" resultType="com.example.spring_mybatis.model_blog.PersonInfo">
select * from blog
</select>
</mapper>按住alt+insert,可在test目錄下生成以上方法的測試方法
import com.example.spring_mybatis.model_blog.PersonInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
@Slf4j
class BlogXMLMapperTest {
private final BlogXMLMapper blogXMLMapper;
@Autowired
public BlogXMLMapperTest(BlogXMLMapper blogXMLMapper) {
this.blogXMLMapper = blogXMLMapper;
}
@Test
void getPersonInfoAll() {
List<PersonInfo> personInfoAll = blogXMLMapper.getPersonInfoAll();
log.info("查詢成功,personInfoAll:{}",personInfoAll.toString());
}
}運行結(jié)果:

2.5 動態(tài)SQL
動態(tài)SQL:指在程序運行時根據(jù)條件或參數(shù)動態(tài)生成的SQL語句。與靜態(tài)SQL相比,動態(tài)SQL更具靈活性,適用于需要根據(jù)不同條件構(gòu)建查詢的場景。例如,在某些web/app進行賬號注冊時會出現(xiàn)非必填選項
- mybatis的注解和xml兩種方式都能實現(xiàn)動態(tài)SQL,但xml較為方便,所以下文使用xml來實現(xiàn)動態(tài)SQL
2.5.1 trim標簽
作用:用于自定義字符串截取規(guī)則。包含四個屬性:
- prefix:最終結(jié)果添加前綴
- suffix:最終結(jié)果添加后綴
- prefixOverrides:去除首部指定內(nèi)容
- suffixOverrides:去除尾部指定內(nèi)容
2.5.2 if標簽
作用:用于條件判斷,通常在where或set語句中使用。當test表達式的值為true時,包含標簽內(nèi)的SQL片段
<insert id="addPersonInfo">
insert into blog
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
</trim>
values
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id},
</if>
<if test="name != null">
#{name},
</if>
<if test="age != null">
#{age},
</if>
</trim>
</insert>2.5.3 where標簽
作用:替代SQL中的where關鍵字。當if條件成立時才會加入SQL片段,并自動去除第一個子句的and/or
<select id="getPersonInfoByNameAndAge">
select * from blog
<where>
<if test="name != null">
and name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
</where>
</select>2.5.4 set標簽
作用:用于update語句。當if條件成立時才會加入SQL片段,并自動去除最后一個子句的逗號、
<update id="updatePersonInfo">
update blog
<set>
<if test="name != null">
name = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
</set>
<where>
and id = #{id}
</where>
</update>2.5.5 foreach標簽
作用:用于集合遍歷。主要屬性:
- collection:集合參數(shù)名
- item:當前元素變量名
- open/close:包圍符號
- separator:分隔符
@Test
void getPersonInfoById() {
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
List<PersonInfo> personInfoById = blogXMLMapper.getPersonInfoById(ids);
System.out.println(personInfoById);
} <select id="getPersonInfoById" resultType="com.example.spring_mybatis.model_blog.PersonInfo">
select * from blog
where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>2.5.6 include標簽
作用:用于引用SQL片段,通過refid指定要引用的片段id。需配合sql標簽使用,實現(xiàn)代碼復用
<sql id="collection">
id,name,age
</sql>
<select id="getPersonInfoAll" resultType="com.example.spring_mybatis.model_blog.PersonInfo">
select
<include refid="collection">
</include>
from blog
</select>2.6 主鍵返回
主鍵返回:指在數(shù)據(jù)庫插入操作后,自動獲取剛插入記錄的主鍵值。在mybatis中使用注解和xml都能獲取到返回的主鍵
1.注解實現(xiàn)
@Mapper
public interface BlogMapper {
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into blog values (#{id},#{name},#{age})")
Integer addPerson(PersonInfo person);
}
@SpringBootTest
@Slf4j
class BlogMapperTest {
private final BlogMapper blogMapper;
@Autowired
public BlogMapperTest(BlogMapper blogMapper) {
this.blogMapper = blogMapper;
}
@Test
void addPerson() {
PersonInfo personInfo = new PersonInfo(null, "黃忠", 60);
Integer ret = blogMapper.addPerson(personInfo);
log.info("添加成功,影響行數(shù):{},返回的主鍵值:{}",ret.toString(),personInfo.getId());//添加成功,影響行數(shù):1,返回的主鍵值:6
}
}
2.通過xml實現(xiàn)
@SpringBootTest
@Slf4j
class BlogXMLMapperTest {
private final BlogXMLMapper blogXMLMapper;
@Autowired
public BlogXMLMapperTest(BlogXMLMapper blogXMLMapper) {
this.blogXMLMapper = blogXMLMapper;
}
@Test
void addPersonInfo() {
PersonInfo personInfo = new PersonInfo();
personInfo.setAge(40);
personInfo.setName("曹操");
Integer ret = blogXMLMapper.addPersonInfo(personInfo);
log.info("添加成功,影響行數(shù):{},返回的主鍵值:{}",ret.toString(),personInfo.getId());//添加成功,影響行數(shù):1,返回的主鍵值:7
}
} <insert id="addPersonInfo" useGeneratedKeys="true" keyProperty="id">
insert into blog
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
</trim>
values
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id},
</if>
<if test="name != null">
#{name},
</if>
<if test="age != null">
#{age},
</if>
</trim>
</insert>
2.7 預編譯/即時SQL
預編譯SQL(Prepared Statements):SQL語句在程序運行前被預先編譯并存儲在數(shù)據(jù)庫中。執(zhí)行時只需傳遞參數(shù),無需重新編譯SQL語句
- 安全性高:通過參數(shù)化查詢避免SQL注入攻擊。參數(shù)化查詢是一種將SQL語句與用戶輸入數(shù)據(jù)分離的數(shù)據(jù)庫操作方式,查詢語句中使用占位符(如?、@param等)代替直接拼接用戶輸入,執(zhí)行時通過預編譯機制將參數(shù)動態(tài)綁定到占位符位置
- 性能優(yōu)化:編譯一次,多次執(zhí)行,減少數(shù)據(jù)庫開銷
即時SQL(Dynamic SQL):在程序運行時動態(tài)生成并立即編譯執(zhí)行,每次執(zhí)行都可能涉及完整的SQL解析和編譯過程
- 靈活性高:可根據(jù)運行時條件動態(tài)拼接SQL語句
- 潛在風險:直接拼接用戶輸入可能導致SQL注入
- 性能開銷:每次執(zhí)行需重新編譯
#占位符會使用預編譯機制,將參數(shù)值安全地綁定到SQL語句中,防止SQL注入攻擊。MyBatis會將#替換為?,然后通過JDBC的預編譯功能設置參數(shù)值$占位符直接進行字符串替換,將參數(shù)值拼接到SQL語句中,不會進行預編譯或轉(zhuǎn)義處理
SQL注入攻擊:當惡意輸入" 'or 1 = '1 "時
1.預編譯SQL
@Select("select * from blog where name= #{name}")
List<UserInfo> queryByName(String name)預編譯SQL會根據(jù)參數(shù)的類型判斷是否需要加引號,上述name參數(shù)是String類型,需要加引號,這就是參數(shù)化查詢的作用。最終SQL:
select * from blog where name = " 'or 1='1 "; # 整個 'or 1='1 會作為name的值
2.即時SQL
@Select("select * from blog where name= '${name}'")
List<UserInfo> queryByName(String name)即時SQL不會判斷參數(shù)類型從而是否添加引號,所以需要手動加上單引號。最終SQL:
select * from blog where name = ''or 1 = '1'; # 因為1=1是恒等式,所以該表的數(shù)據(jù)會被全部查詢出來,這就是SQL注入
到此這篇關于Spring配置文件和mybatis的文章就介紹到這了,更多相關Spring配置文件和mybatis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Security 自動踢掉前一個登錄用戶的實現(xiàn)代碼
這篇文章主要介紹了Spring Security 自動踢掉前一個登錄用戶的實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
基于數(shù)據(jù)庫的用戶認證實現(xiàn)SpringBoot3整合SpringSecurity6的過程
這篇文章主要介紹了基于數(shù)據(jù)庫的用戶認證實現(xiàn)SpringBoot3整合SpringSecurity6的過程,本文通過實例圖文并茂的形式給大家介紹的非常詳細,感興趣的朋友一起看看吧2025-05-05
jvm調(diào)優(yōu)的幾種場景(小結(jié))
本文主要介紹了jvm調(diào)優(yōu)的幾種場景,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
MyBatis中?@Mapper?和?@MapperScan?的區(qū)別與使用解析
本文介紹了SpringBoot中MyBatis的兩個常用注解:@Mapper和@MapperScan,@Mapper用于標記單個Mapper接口,而@MapperScan用于批量掃描指定包下的所有Mapper接口,兩者都有各自適用的場景,選擇合適的注解可以提高開發(fā)效率并使代碼更加簡潔,感興趣的朋友一起看看吧2025-01-01

