欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java之@TableField注解的用法解析

 更新時間:2025年01月26日 08:52:18   作者:孫 悟 空  
MyBatis-Plus的@TableField注解用于控制實(shí)體類字段與數(shù)據(jù)庫表字段的映射關(guān)系,支持字段映射、忽略、插入和更新控制、自定義填充策略和類型轉(zhuǎn)換等

Java @TableField注解用法

  • @TableField 是 MyBatis-Plus 中的一個注解,用于標(biāo)識實(shí)體類字段與數(shù)據(jù)庫表字段的映射關(guān)系。它可以用來控制某些字段在數(shù)據(jù)庫操作中是否被映射、是否參與數(shù)據(jù)庫的插入、更新等操作,或者設(shè)置字段在數(shù)據(jù)庫中的實(shí)際名稱。
  • @TableField 可以使得代碼更加靈活,避免了與數(shù)據(jù)庫字段名不一致時的麻煩,也使得字段的自動填充和映射控制更加精細(xì)。

常見的作用和用法

1.字段映射與數(shù)據(jù)庫字段名不一致

如果實(shí)體類字段名與數(shù)據(jù)庫表字段名不一致,可以使用 @TableField 注解來指定對應(yīng)的數(shù)據(jù)庫字段名。

public class User {
    @TableField("user_name")  // 數(shù)據(jù)庫表中字段名為 user_name
    private String username;
}

2.忽略某個字段

如果某個字段不需要參與數(shù)據(jù)庫操作(例如不需要插入或更新),可以使用 @TableField(exist = false) 來標(biāo)記。

public class User {
    @TableField(exist = false)  // 表示該字段不映射到數(shù)據(jù)庫
    private String temporaryField;
}

3.指定字段是否參與插入、更新操作

@TableField 可以與 insertupdate 屬性一起使用,指定該字段在插入或更新時是否參與操作。

public class User {
    @TableField(fill = FieldFill.INSERT)  // 僅在插入時填充
    private Date createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)  // 在插入和更新時都填充
    private Date updateTime;
}

4.自定義填充策略

MyBatis-Plus 提供了自動填充的功能,可以通過 @TableField 注解的 fill 屬性指定某些字段在插入或更新時由 MyBatis-Plus 自動填充,例如時間戳、創(chuàng)建者等。

@TableField(fill = FieldFill.INSERT)  // 在插入時自動填充
private Date createTime;

5.設(shè)置數(shù)據(jù)庫字段的類型

@TableField 注解還可以設(shè)置數(shù)據(jù)庫字段的類型,例如 typeHandler 屬性可以指定自定義的類型處理器,用于特定的字段類型轉(zhuǎn)換。

@TableField(typeHandler = MyCustomTypeHandler.class)
private String customField;

常用屬性

  • value:數(shù)據(jù)庫字段名(默認(rèn)是實(shí)體類字段名)。
  • exist:是否映射到數(shù)據(jù)庫,false 表示不映射,true 表示映射(默認(rèn)值為 true)。
  • fill:字段填充策略,FieldFill.INSERTFieldFill.UPDATE、FieldFill.INSERT_UPDATE,可以指定字段何時進(jìn)行自動填充。
  • typeHandler:指定字段的類型處理器,用于自定義字段類型轉(zhuǎn)換。

示例

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import java.util.Date;

@TableName("user")
public class User {

    private Long id;
    
    @TableField("user_name") // 映射數(shù)據(jù)庫中的 "user_name" 字段
    private String username;
    
    @TableField(exist = false) // 不映射數(shù)據(jù)庫中的字段
    private String temporaryField;
    
    @TableField(fill = FieldFill.INSERT) // 在插入時填充
    private Date createTime;
    
    @TableField(fill = FieldFill.INSERT_UPDATE) // 在插入和更新時填充
    private Date updateTime;

    // Getter and Setter methods
}

總結(jié)

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論