MyBatis-Plus 實現?sp_id_path
?與?id
?同步的方案
要實現新增時?sp_id_path
?自動與?id
?保持一致,需要在實體類和插入邏輯中做相應處理。MyBatis-Plus 提供了幾種方式來實現這一需求:
方案一:使用 MyBatis-Plus 的自動填充功能
這是最優雅的解決方案,通過實現?MetaObjectHandler
?接口,在插入前自動設置?sp_id_path
?的值:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;@Component
public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {// 獲取當前實體對象Object entity = metaObject.getOriginalObject();// 只處理 DsteSpConfigNew 實體if (entity instanceof DsteSpConfigNew) {DsteSpConfigNew config = (DsteSpConfigNew) entity;// 若 sp_id_path 未手動設置,則在插入前設置為 id 值if (config.getSpIdPath() == null) {// 注意:此處 id 可能還未生成,需要特殊處理// 下面會提供具體實現方式}}}@Overridepublic void updateFill(MetaObject metaObject) {// 更新填充邏輯}
}
方案二:在插入后更新?sp_id_path
由于?id
?是自增主鍵,插入前無法獲取,可分兩步實現:
- 先插入記錄,獲取生成的?
id
- 立即更新?
sp_id_path
?為該?id
@Service
public class DsteSpConfigNewService {@Autowiredprivate DsteSpConfigNewMapper configMapper;@Transactionalpublic void saveConfig(DsteSpConfigNew config) {// 1. 插入記錄,此時會自動生成 idconfigMapper.insert(config);// 2. 獲取生成的 idLong id = config.getId();// 3. 更新 sp_id_path 為 id 值DsteSpConfigNew updateEntity = new DsteSpConfigNew();updateEntity.setId(id);updateEntity.setSpIdPath(String.valueOf(id));configMapper.updateById(updateEntity);}
}
方案三:使用數據庫觸發器(推薦)
數據庫層面的觸發器可以更可靠地保證?sp_id_path
?與?id
?的一致性:
DELIMITER $$
CREATE TRIGGER after_dste_sp_config_new_insert
AFTER INSERT ON dste_sp_config_new
FOR EACH ROW
BEGIN-- 將新記錄的 sp_id_path 更新為 id 值UPDATE dste_sp_config_new SET sp_id_path = NEW.id WHERE id = NEW.id;
END$$
DELIMITER ;
這種方式無需修改 Java 代碼,完全由數據庫自動處理,但需要注意觸發器可能帶來的性能影響。
實體類配置
確保實體類中包含這兩個字段,并使用正確的注解:
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;@Data
@TableName("dste_sp_config_new")
public class DsteSpConfigNew {@TableId(type = IdType.AUTO)private Long id;private String spName;private Long projectId;private String spIdPath;private String spNamePath;private Long parentSpId;private Integer spStatus;private LocalDateTime createAt;private LocalDateTime updateAt;private LocalDateTime deleteAt;
}