我收到字段“id”在我的 Java Hibernate 数据库中没有默认值

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

这是一个将存储使用 Hibernate 构建的温度的数据库:


import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Entity
@NoArgsConstructor
@EntityListeners(AuditingEntityListener.class)
@Data
public class TempTable { //Den viktigaste tabellen i DBMS, här lagras data rått
    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Long Id;

    private Float temperatures;

    @CreatedDate
    @LastModifiedBy
    private LocalDateTime timestamp; // ' 2023-09-24T12:34:56.789 '

    @Transient
    public String getFormattedTimestamp(){ //Denna metod påverkar inte data som finns i tabellerna, den är framtagen för enkelt kunna formatera data
        if (timestamp != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 'hour' HH : 'minute' mm : 'seconds' : ss.SSS");
            return timestamp.format(formatter);
        }
        System.out.println("Could not format datetime");
        return "";
    }

    @OneToMany(mappedBy = "tempTable", cascade = CascadeType.ALL)
    private List<WarningTable> warningTables = new ArrayList<>();

    public TempTable(Long Id, Float temperatures){
        this.Id = Id;
        this.temperatures = temperatures;
    }
}

当我尝试在工作台中运行此 SQL 查询时:

INSERT INTO temp_table (temperatures) VALUES (22.5);

我收到此错误

0    16  18:30:49    INSERT INTO temp_table (temperatures) VALUES (22.5) Error Code: 1364. Field 'id' doesn't have a default value   0.000 sec

这很奇怪吗? id 应该自动递增,我已经添加了正确的注释。所以有人可以指出任何问题吗?

或者是因为我的数据库是空的?

这就是表格目前的样子:

   id,             bigint,         NO,         PRI,     NULL,
   temperatures,   float,          YES,,                NULL,
   timestamp,      datetime(6),    YES,,                NULL,```

I converted the table into a csv file so that I could gather information about the table
java sql spring hibernate database-schema
1个回答
0
投票

请注意:当您在 Hibernate 中使用

GenerationType.AUTO
时,它通常会选择数据库中的
SEQUENCE
而不是
AUTO_INCREMENT
功能。这意味着该列的默认值在数据库中为
null

如果您想更改此设置,请考虑使用

GenerationType.IDENTITY
GenerationType.TABLE
。例如,
GenerationType.TABLE
将利用 MariaDB 等数据库中的
AUTO_INCREMENT
功能。

希望这有帮助!

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