出现这个注解原因
如果前端没有传递这个字段,MyBatis-Plus在执行插入操作时不会处理这个标记为自动填充的字段。
为了在插入数据时自动填充这个字段,你需要实现一个字段填充的拦截器MetaObjectHandler
注解基本使用
@TableField(fill = FieldFill.INSERT) 是 MyBatis-Plus 中的注解,用于设置实体类中对应的字段在插入时需要自动填充。
@TableField 注解表示该字段是数据库字段,支持的属性包括:value、exist、el、condition、update、insertStrategy、updateStrategy、whereStrategy、fill。
其中,fill 属性就是用来设置自动填充策略的。FieldFill 是一个枚举类型,它定义了 4 种自动填充策略,分别为:
DEFAULT: 不进行任何填充
INSERT: 插入时填充
UPDATE: 更新时填充
INSERT_UPDATE: 插入和更新时都填充
举例
项目中的接受实体类和表对应
package com.njry.modules.system.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.njry.base.BaseEntity;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.copier.CopyOptions;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
/**
* @description /
* @author WJ
* @date 2024-04-19
**/
@Data
@TableName("T_ATOM_BUSI_CATEGORY")
public class TAtomBusiCategory extends BaseEntity implements Serializable {
@NotNull(groups = BaseEntity.Update.class)
@TableId(value="category_id", type = IdType.INPUT)
@ApiModelProperty(value = "ID", hidden = true)
private Long id;
@ApiModelProperty(value = "业务类别ID")
private Long categoryId;
@NotEmpty(message = "业务类别名称不能为空")
@Length(min = 1 , max = 40 , message = "名字字节长度1~40")
@ApiModelProperty(value = "业务类别名称")
private String categoryName;
@ApiModelProperty(value = "上级ID")
private Long superiorId;
@ApiModelProperty(value = "层级")
private Integer categoryLev;
@ApiModelProperty(value = "排序")
private Integer orderBy;
@TableField(exist = false)
private List<TAtomBusiCategory> children;
@ApiModelProperty(value = "子业务分类数目", hidden = true)
private Integer subCount = 0;
@ApiModelProperty(value = "创建人ID")
private String createId;
@ApiModelProperty(value = "创建时间")
private Date createDate;
@Length(min = 1 , max = 10 , message = "业务类别英文名称长度1~10")
@ApiModelProperty(value = "业务类别英文名称")
private String categoryNameEn;
public void copy(TAtomBusiCategory source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
public Boolean getHasChildren() {
return subCount > 0;
}
public Boolean getLeaf() {
return subCount <= 0;
}
public String getLabel() {
return categoryName;
}
}
这里项目几乎所有实体类如果对应表有通用的创建人,创建时间,更新人,更新时间,都会继承 BaseEntity
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.njry.base;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Timestamp;
/**
* 通用字段, is_del 根据需求自行添加
* @author Zheng Jie
* @Date 2019年10月24日20:46:32
*/
@Getter
@Setter
public class BaseEntity implements Serializable {
@CreatedBy
@TableField(fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建人", hidden = true)
private String createBy;
@LastModifiedBy
@TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新人", hidden = true)
private String updateBy;
@TableField(fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建时间", hidden = true)
private Timestamp createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间", hidden = true)
private Timestamp updateTime;
/* 分组校验 */
public @interface Create {}
/* 分组校验 */
public @interface Update {}
@Override
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this);
Field[] fields = this.getClass().getDeclaredFields();
try {
for (Field f : fields) {
f.setAccessible(true);
builder.append(f.getName(), f.get(this)).append("\n");
}
} catch (Exception e) {
builder.append("toString builder encounter an error");
}
return builder.toString();
}
}
项目里时间好获取,但是人都是框架在登录时候就把用户保存到全局
这里取用户是 封装的类SecurityUtils下面的getCurrentUsername方法
下面代码就是这个方法
/**
* 获取系统用户名称
*
* @return 系统用户名称
*/
public static String getCurrentUsername() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
}
// Method[] m = authentication.getPrincipal().getClass().getDeclaredMethods();
// for (int i = 0; i < m.length; i++) {
// System.out.println(m[i].getName());
// }
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("登陸報錯的系統用戶名"+userDetails);
return userDetails.getUsername();
}
throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息");
}
为啥能在SecurityContextHolder.getContext().getAuthentication()获取到Authentication authentication?
项目用jwt的usernamepassword登录时候保存的
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(authUser.getUsername(), password);
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);