SpringBoot13-小细节

一、开启Mybatis驼峰命名和下划线命名的转换

MyBatis 中,想让数据库字段的下划线命名自动映射到 Java 实体的驼峰命名(例如 user_name → userName),只需要在配置里 开启自动下划线转驼峰 功能即可。


1. 在 application.ymlapplication.properties 中配置(推荐)

如果你用的是 Spring Boot + MyBatis,直接在配置文件里加上:

application.yml

复制代码
mybatis:
  configuration:
    map-underscore-to-camel-case: true

application.properties

复制代码
mybatis.configuration.map-underscore-to-camel-case=true

注意:如果你用的是 MyBatis-Plus,配置同样有效,也可以用它自己的配置:

复制代码
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true

2. 如果是纯 MyBatis(XML 配置)

在 MyBatis 的 mybatis-config.xml 里设置:

XML 复制代码
<configuration>
    <settings>
        <!-- 开启自动下划线转驼峰 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

3. 注意事项

  • 数据库字段名要用 小写+下划线 格式,如:user_idcreate_time

    Java 实体用驼峰:userIdcreateTime

  • 如果字段名和属性名完全不匹配(比如列叫 USERID 而属性是 userId),就算开启了也不会自动映射,需要用 @ResultresultMap 指定。

  • 如果你用了 MyBatis GeneratorMyBatis-Plus 自动生成代码,通常生成的实体已经和表字段对应好了,就不一定需要这个设置。


总结

在 Spring Boot 中最简单的方式:

复制代码
mybatis:
  configuration:
    map-underscore-to-camel-case: true

就能让 user_nameuserName 自动映射。

如果是传统 MyBatis 项目,就在 mybatis-config.xml 里加 <setting name="mapUnderscoreToCamelCase" value="true"/>


补充:@Result 和 resultMap

MyBatis 中,默认的自动映射规则是:

列名 ↔ Java 属性名 按下划线转驼峰规则自动匹配(如果在配置里打开 mapUnderscoreToCamelCase=true)。

如果列名和属性名完全不对应(既不相同,也无法通过下划线转驼峰得到),就无法自动映射,必须手工指定。

下面用一个具体例子演示。


❌ 自动映射失败示例

假设数据库表:

sql 复制代码
CREATE TABLE t_user (
    USERID    VARCHAR(32),
    USER_NAME VARCHAR(50)
);

Java 实体:

java 复制代码
public class User {
    private String userId;   // 注意:列名是 USERID
    private String username; // 注意:列名是 USER_NAME
    // getter / setter 省略
}
  • 配置里已经开启:

    XML 复制代码
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
  • MyBatis 查询:

    XML 复制代码
    <select id="selectAll" resultType="User">
        SELECT USERID, USER_NAME FROM t_user
    </select>

结果:

  • userId 可以映射到 USERID(因为大小写不敏感,MyBatis 默认支持),✅

  • username 无法自动映射,因为列是 USER_NAME,驼峰转换后会是 userName,而实体叫 username(少了驼峰的大写 N)。

自动映射规则只负责把 USER_NAMEuserName,不会再去匹配 username


✅ 正确做法:用 @Results / resultMap

方式一:注解版
java 复制代码
@Mapper
public interface UserMapper {

    @Select("SELECT USERID, USER_NAME FROM t_user")
    @Results(id = "userMap", value = {
        @Result(column = "USERID", property = "userId"),
        @Result(column = "USER_NAME", property = "username")
    })
    List<User> selectAll();
}
方式二:XML 配置版
XML 复制代码
<resultMap id="userMap" type="User">
    <result column="USERID" property="userId"/>
    <result column="USER_NAME" property="username"/>
</resultMap>

<select id="selectAll" resultMap="userMap">
    SELECT USERID, USER_NAME FROM t_user
</select>

总结

  • MyBatis 自动映射只能处理:

    • 列名与属性名相同(忽略大小写),或

    • 列名下划线转驼峰后与属性名相同。

  • 如果列名和属性名完全对不上(USERIDuserId 能自动,但 USER_NAMEusername 就不行),必须用 @Result / <resultMap> 明确指定

  • 因此当遇到命名规则不一致的老库或第三方表时,一定要写 resultMap 或注解映射。


二、控制台打印出实际执行的 SQL 语句及参数

在 Spring Boot + MyBatis 项目中,想让控制台打印出实际执行的 SQL 语句及参数,可以用以下几种常见配置方式:

最推荐:application.yml 配置

java 复制代码
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

这样启动项目后,控制台会直接输出完整 SQL,包括参数值和执行时间。


三、@JsonIgnore讲解

@JsonIgnoreJackson(Spring Boot 默认使用的 JSON 序列化/反序列化库)提供的注解,用来在对象与 JSON 之间进行转换时忽略某个字段


2-1. 基本作用

  • 序列化时忽略

    把对象转成 JSON 时,标注了 @JsonIgnore 的字段 不会出现在返回的 JSON 中

  • 反序列化时忽略

    把 JSON 转成对象时,标注了 @JsonIgnore 的字段 不会从 JSON 中读取值并赋给对象


示例代码

java 复制代码
import com.fasterxml.jackson.annotation.JsonIgnore;

public class User {
    private String username;
    
    @JsonIgnore
    private String password;  // 不希望返回给前端
    
    private String email;

    // getters and setters
}
控制器示例
java 复制代码
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping
    public User getUser() {
        User u = new User();
        u.setUsername("Tom");
        u.setPassword("123456");
        u.setEmail("tom@example.com");
        return u;
    }
}
返回结果
复制代码
{
  "username": "Tom",
  "email": "tom@example.com"
}

password 字段被自动忽略了。


2-2. 常见使用场景

场景 说明
隐藏敏感信息 比如密码、身份证号、token,不希望返回给前端。
避免循环引用 有双向关联时,防止无限递归序列化(但更推荐用 @JsonManagedReference / @JsonBackReference)。
只在内部使用 某些内部计算字段只在后台用,不需要暴露给外部接口。

2-3. 与其他注解的区别

注解 作用
@JsonIgnore 永远忽略此字段,序列化 & 反序列化都跳过。
@JsonProperty 自定义 JSON 字段名称,或者强制包含某个字段。
@JsonIgnoreProperties 批量忽略指定的字段,作用在类上。
@JsonInclude 控制字段为空时是否序列化(例如只序列化非 null 的字段)。

对比 @JsonIgnoreProperties

java 复制代码
@JsonIgnoreProperties({"password","id"})
public class User { ... }

一次性忽略多个属性,适合类上统一处理。


⚠️ 注意事项

  • @JsonIgnore 只对 Jackson 有效(Spring Boot 默认是 Jackson),如果换成 Gson/Fastjson 不会生效。

  • 如果一个字段加了 @JsonIgnore反序列化也不会给它赋值 。如果你只想"序列化时忽略,反序列化时接收",用@JsonProperty

    java 复制代码
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)

    例如:

    java 复制代码
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password; 

    这样:前端可以传 password,但返回 JSON 时不显示。


总结

@JsonIgnore 用于 完全跳过字段(序列化 & 反序列化都忽略)。

  • 如果只想 返回时隐藏 ,但仍能接收前端传值,用 @JsonProperty(access = WRITE_ONLY)

  • 如果要一次性忽略多个属性,用 @JsonIgnoreProperties


四、在 Postman 里如果想给所有请求统一加上某些请求头

写预请求脚本时,直接在右侧的 Scripts → Pre-req 里写就可以了,相当于旧版的 Pre-request Script

如果你想设置 token 之类的内容,可以在这里写:

此时,JWT-test collection下的所有的请求,都会自动在请求头中带上这个Authorization

推荐用 pm.request.headers.upsert() 而不是 addHeader()

addHeader 每次都会追加一个新 Header;

如果你在一个集合或请求中多次运行,可能会出现多个重复的 Authorization 字段。

upsert有则更新、没有则新增。


五、 MyBatis 在启动时没有加载到 UserMapper.insert 这条语句

mapper-locations 没配置或路径不对(90% 的锅)

确保 UserMapper.xml 被扫描到。放在 src/main/resources/mapper/UserMapper.xml,并在 application.yml(或 properties)里写:

示例:UserMapper.xml 放在 src/main/java/org/example/mapper/xml 下面。

MyBatis 只会去 classpath 的资源目录找 XML。默认只有 src/main/resources 会被打进 classpath;

src/main/java 里的 .xml 不会被当作资源复制,于是启动时根本扫不到这份 mapper,所以出现。

解决方式:

1、application.yml文件中配置:mapper-locations位置

2、确保 IDE/构建 会把这些 xml 复制到 target/classes/org/example/mapper/xml/。可用 Maven 资源复制:

相关推荐
后端小张6 分钟前
【JAVA 进阶】重生之我要学会 JUC 并发编程
java·spring boot·spring·java-ee·并发编程·安全架构·juc
九转成圣1 小时前
JWT 全面解析与 Spring Boot 实战教程
java·spring boot·后端
=>>漫反射=>>1 小时前
【Spring Boot Starter 设计思考:分离模式是否适用于所有场景】
java·spring boot·后端·设计规范·自动装配
陈老师还在写代码3 小时前
springboot 打包出来的 jar 包的名字是在哪儿决定的
spring boot·后端·jar
m0_5642641810 小时前
IDEA DEBUG调试时如何获取 MyBatis-Plus 动态拼接的 SQL?
java·数据库·spring boot·sql·mybatis·debug·mybatis-plus
熊小猿11 小时前
在 Spring Boot 项目中使用分页插件的两种常见方式
java·spring boot·后端
paopaokaka_luck11 小时前
基于SpringBoot+Vue的助农扶贫平台(AI问答、WebSocket实时聊天、快递物流API、协同过滤算法、Echarts图形化分析、分享链接到微博)
java·vue.js·spring boot·后端·websocket·spring
老华带你飞11 小时前
机器人信息|基于Springboot的机器人门户展示系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·机器人·论文·毕设·机器人门户展示系统
小蒜学长13 小时前
springboot酒店客房管理系统设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端
软件架构师-叶秋15 小时前
spring boot入门篇之开发环境搭建
java·spring boot·后端