(Java实体类比表字段多处理方案)注解忽略实体类属性

发布时间 2023-08-17 09:34:37作者: 白玉神驹

背景

实体类多添加了几个字段用于查询,如果项目中使用了mybatis或mybatisplus会导致找不到表中字段的错误

Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'create_start_time' in 'field list'

解决

项目中使用mybatis

import org.springframework.data.annotation.Transient;
@Transient
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date startTime;
@Transient
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date endTime;

项目中使用mybatisplus

import com.baomidou.mybatisplus.annotation.TableField;
@TableField(exist = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date startTime;
@TableField(exist = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date endTime;
//exist = false 表示该属性不为数据库表字段,但又是必须使用的。

例子

<if test="createStartTime != null and createEndTime != null">and DATE_FORMAT(u.create_time,'%Y-%m-%d %H:%i:%s')
        >= #{createStartTime} and #{createEndTime} >= DATE_FORMAT(u.create_time,'%Y-%m-%d %H:%i:%s')
</if>

//由于项目中使用了mybatisplus的lambdaQuery()需要在实体类中添加忽略注解 
    @ApiModelProperty(value = "注册开始时间")
    @TableField(exist = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createStartTime;
    @ApiModelProperty(value = "注册结束时间")
    @TableField(exist = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createEndTime;