Spring:java.sql.SQLException:字段“**”没有默认值

问题描述 投票:0回答:2

我的实体是一个具有默认值的数据类,并且在 API 调用后在服务器中接收 json,但由于某种原因,数据类中不存在的一个字段始终为 null。

@Entity
@Table(name = "checking_point")
data class CheckingPointEntity(

    @Column(nullable = false, unique = false, length = 500)
    open var name: String = "",

    @Column(nullable = false, unique = false, length = 500)
    open var description: String = "",

    @Column(nullable = false)
    open var cpTypeId: Int = 0,

    @Column(nullable = false)
    open var isCumulative: Boolean = false,

    @Column(nullable = false)
    open var cpCategoryGroupId: Long = 0L,

    @Column(nullable = false)
    open var isTemplate: Boolean = false,

    @Column(nullable = false)
    open var isTopTemplate: Boolean = false

) : BkpBaseEntity1()

BastEntity1:

@MappedSuperclass
open class  BkpBaseEntity1 {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    open var id:Long = 0L

    // **************************************************************************
    // *****    Below 4 columns should be there in each and every table   *******
    // **************************************************************************

    @Column(nullable = false, updatable = false,  columnDefinition = "varchar(100) default 'adhoc-sql'")
    open var dbCreateSource: String = BkpConstants.DB_CREATE_SOURCE_NAME;


    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss" )
    @Temporal(TemporalType.DATE)
    @Column(nullable = false,insertable = false, updatable=false, columnDefinition = "datetime DEFAULT now()")
    open var dbCreateDts: Date = Date() //Do not set this field. It will be populated by DB.


    @Column(nullable = false, columnDefinition = "varchar(100) default 'adhoc-sql'")
    open var dbUpdateSource: String = BkpConstants.DB_CREATE_SOURCE_NAME;

    @Column(nullable = false, insertable = false, updatable=false, columnDefinition = "datetime  NOT NULL DEFAULT now() on update now()")
    @Temporal(TemporalType.DATE)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    open var dbUpdateDts: Date = Date() //Do not set this field. It will be populated by DB.

}

控制器:

@RequestMapping(path = [ControllerEndPoints.AddCheckingPoint], method = [RequestMethod.POST])
    fun addCheckingPoint(@RequestBody(required = true) reqData: ChartServerVo): ResponseEntity<ChartAck> {
        mLog("in add cp ")
        var cpId = 0L
        var pcId = 0L
         val cpDto : CheckingPointDto = reqData.checkingPointDto
        val gson = GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
        val payload = gson.toJson(reqData)
        mLog("json: \n json $payload ")
            mLog("json: saved cpDto name ${cpDto.name}, description ${cpDto.description} cpTypeId ${cpDto.cpTypeId} isCumulative ${cpDto.isCumulative} categoryGroupId ${cpDto.cpCategoryGroupId} isTemplate")
            cpr.save(cpDto.toEntity())
...................
}

服务器收到的Json包含所有字段

    {"checkingPointDto":{"name":"demo","description":"","cpTypeId":1,"isCumulative":false,"cpCategoryGroupId":16,"isTemplate":false,"isTopTemplate":false,"id":0,"dbCreateSource":"","dbCreateDts":"2022-03-08 21:07:32","dbUpdateSource":"","dbUpdateDts":"2022-03-08 21:07:32"},"purusharthChartCpMappingDto":{"id":0,"purusharthChartId":16466443,"cpId":0},"purusharthChartDto":{"id":16466443,"adminID":8,"name":"demo","description":"","userId":8,"startDate":"2022-03-08 21:07:32","endDate":"2022-12-30 21:07:32","isSelfChart":false},"isNewchart":false} 

该错误表示实体中不存在的字段

cp_type_id
为空。

java.sql.SQLException: Field 'cp_type_id' doesn't have a default value
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.25.jar:8.0.25]

我可以找到此字段的唯一其他位置是在 .sql 文件中。 我是春天的新手,我不知道它应该做什么。就我的 sql 知识而言,它对我来说看起来不错

create table checking_point(
    id int primary key NOT NULL auto_increment,
    name_str_id int,
    foreign key(name_str_id) references localization(id),
    description_str_id varchar(500),
    cp_type_id int,
    foreign key(cp_type_id) references dim_cp_type(id),
    cp_category_group_id int,
    foreign key(cp_category_group_id) references cp_category_group(id),
    repeat_type_id int,
    foreign key(repeat_type_id) references dim_repeat_type(id),
    cp_repeat_reminder_id int,
    is_template boolean,
    is_top_template boolean,
    db_create_dts date,
    db_create_source nvarchar(320),
    db_updated_dts date,
    db_update_source nvarchar(320)
);

我错过了什么?为什么该提交的文件甚至不存在于相关实体中,导致此问题?

spring spring-boot
2个回答
1
投票

您是否尝试过通过SQL查询为其分配默认值? 如果您已经有数据库 GUI(如 MySQL Workbench),您只需执行此附加查询即可将字段设置为默认值。

ALTER TABLE `checking_point` ALTER `cp_type_id` SET DEFAULT NULL

或者您可以更改已有的 sql 查询

create table checking_point(
    id int primary key NOT NULL auto_increment,
    name_str_id int,
    foreign key(name_str_id) references localization(id),
    description_str_id varchar(500),
    cp_type_id int DEFAULT NULL, <-HERE
    foreign key(cp_type_id) references dim_cp_type(id),
    cp_category_group_id int,
    foreign key(cp_category_group_id) references cp_category_group(id),
    repeat_type_id int,
    foreign key(repeat_type_id) references dim_repeat_type(id),
    cp_repeat_reminder_id int,
    is_template boolean,
    is_top_template boolean,
    db_create_dts date,
    db_create_source nvarchar(320),
    db_updated_dts date,
    db_update_source nvarchar(320)
);

通过分配 te 默认值,您将停止获得 cp_type_id 的这些类型的异常,同样的方法适用于它所抱怨的任何其他字段。


0
投票

问题

在我的例子中,特定字段注释被错误地应用于表中的字段,导致

null
值出现意外问题。

解决方案

  1. 识别并纠正不正确的注释: 确保字段注释仅正确应用于应引用它们的实体中。

    例如,如果字段注释在实体中应用不正确,请在适当的实体中更正它。

识别和解决类似问题的策略

  1. 转储数据库架构: 导出数据库的架构以查看结构和关系。

    mysqldump --no-data -u yourusername -p yourdatabase > schema_dump.sql
    
  2. 查看架构: 检查转储的架构是否有不正确的注释或外键约束。

  3. 识别不正确的注释: 查找可能被错误应用的注释。确保正确定义外键约束和字段定义。

  4. 测试更改: 更正注释后,测试更改以确保问题得到解决并且应用程序的其他部分不受影响。

GL

© www.soinside.com 2019 - 2024. All rights reserved.