首页 > 解决方案 > 如何使用 Spring Boot JPA 注释来注释 MYSQL 自动增量字段 => 'id' 没有默认值

问题描述

我尝试在我的数据库 Mysql 中上传文件,其中包含限制访问的成员列表,但 ID 自动生成存在问题。(一个例子,这个上传示例,我的文件https://bezkoder.com/spring-boot-upload-file-database/

休眠:插入文档(documentDate,id_file,id_doc_type)值(?,?,?)2021-05-31 10:29:26.008 WARN 900 --- [nio-8081-exec-1] ohengine.jdbc.spi。 SqlExceptionHelper:SQL 错误:1364,SQLState:HY000 2021-05-31 10:29:26.008 错误 900 --- [nio-8081-exec-1] ohengine.jdbc.spi.SqlExceptionHelper:字段 'id' 没有默认值 2021-05-31 10:29:26.021 错误 900 --- [nio-8081-exec-1] oaccC[.[.[/].[dispatcherServlet] :Servlet.service() 用于 servlet [dispatcherServlet]在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 org.springframework.orm.jpa.JpaSystemException:无法执行语句;嵌套异常是 org.hibernate.exception.GenericJDBCException: could not execute statement] 根本原因

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

@Entity
public class Document implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "id_file")
    private FileDB file;
    
    @ManyToOne
    @JoinColumn(name = "id_doc_type")
    private DocumentType type;
    private Date documentDate;
    
    @ManyToMany
    @JoinTable( name = "document_codominium_associations",
                joinColumns = @JoinColumn( name = "id_document" ),
                inverseJoinColumns = @JoinColumn( name = "id_codominium" ) )
    private List<Condominium> lstCodiminium;
    
    @ManyToMany
    @JoinTable( name = "document_coowner_associations",
                joinColumns = @JoinColumn( name = "id_document" ),
                inverseJoinColumns = @JoinColumn( name = "id_coowner" ) )
    private List<CoOwner> lstCoOwner;
}

//// Controler
    @PostMapping("/Documents/upload/{id}")
    public ResponseEntity<ResponseMessage> uploadFile(@PathVariable(name = "id") int id, @RequestParam("file") MultipartFile file) {
      String message = "";
      try {
          documentRepository.findById(id).get().setFile(storageServiceDB.store(file));
        message = "Uploaded the file successfully: " + file.getOriginalFilename();
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
      } catch (Exception e) {
        message = "Could not upload the file: " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
      }
    }
    @PostMapping("/Documents")
    public Document creatDocument(@RequestBody Document d) {
//no image
        return documentRepository.save(d);
    }

在此处输入图像描述

spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB

server.port=8081
server.servlet.session.timeout=1200
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/updb
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.storage.storage_engine=innodb

port=3306
socket="C:/xampp/mysql/mysql.sock"

default-character-set=utf8mb4
[mysqld]
port=3306
socket="C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
pid_file="mysql.pid"

key_buffer=16M
max_allowed_packet=1M
sort_buffer_size=512K
net_buffer_length=8K
read_buffer_size=256K
read_rnd_buffer_size=512K
myisam_sort_buffer_size=8M
log_error="mysql_error.log"

plugin_dir="C:/xampp/mysql/lib/plugin/"

server-id   =1

innodb_data_home_dir="C:/xampp/mysql/data"
innodb_data_file_path=ibdata1:10M:autoextend
innodb_log_group_home_dir="C:/xampp/mysql/data"

innodb_buffer_pool_size=16M

innodb_log_buffer_size=8M
innodb_flush_log_at_trx_commit=1
innodb_lock_wait_timeout=50

sql_mode=NO_ZERO_IN_DATE,NO_ZERO_DATE,NO_ENGINE_SUBSTITUTION
log_bin_trust_function_creators=1

character-set-server=utf8mb4
collation-server=utf8mb4_general_ci
[mysqldump]
max_allowed_packet=16M

[mysql]

[isamchk]
key_buffer=20M
sort_buffer_size=20M
read_buffer=2M
write_buffer=2M

[myisamchk]
key_buffer=20M
sort_buffer_size=20M
read_buffer=2M
write_buffer=2M

[mysqlhotcopy]
Hibernate: create table Document (id integer not null auto_increment, documentDate datetime, id_file varchar(255), id_doc_type integer, primary key (id)) engine=InnoDB
Hibernate: create table document_codominium_associations (id_document integer not null, id_codominium integer not null) engine=InnoDB
Hibernate: create table document_coowner_associations (id_document integer not null, id_coowner integer not null) engine=InnoDB
Hibernate: create table files (id varchar(255) not null, data longblob, name varchar(255), type varchar(255), primary key (id)) engine=InnoDB
Hibernate: create table News (id integer not null auto_increment, message varchar(255), newsDate datetime, primary key (id)) engine=InnoDB
Hibernate: create table Phone (phoneNumber varchar(255) not null, primary key (phoneNumber)) engine=InnoDB
Hibernate: alter table Document add constraint FK1u4rlvkuita670s9axjj6sc98 foreign key (id_file) references files (id)
Hibernate: alter table Document add constraint FKinv0up4vmud0k3twcim8k3gii foreign key (id_doc_type) references document_type (id)
Hibernate: alter table document_codominium_associations add constraint FKmv02ju4buri6f7kkmlteuc1qs foreign key (id_codominium) references Condominium (id)
Hibernate: alter table document_codominium_associations add constraint FKgbs91o6foijrha6h4oerj8c05 foreign key (id_document) references Document (id)
Hibernate: alter table document_coowner_associations add constraint FK8ac3ijqxldw1w5fik87c6vuwj foreign key (id_coowner) references co_owner (id)
Hibernate: alter table document_coowner_associations add constraint FKgqiuqc50nsu3k8w0kwesp8sfp foreign key (id_document) references Document (id)
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Hôte : 127.0.0.1
-- Généré le : lun. 31 mai 2021 à 11:24
-- Version du serveur :  10.4.17-MariaDB
-- Version de PHP : 8.0.0

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Base de données : `updb`
--

-- --------------------------------------------------------

--
-- Structure de la table `document`
--

CREATE TABLE `document` (
  `id` int(11) NOT NULL,
  `documentDate` datetime DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `id_file` varchar(255) DEFAULT NULL,
  `id_doc_type` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Index pour les tables déchargées
--

--
-- Index pour la table `document`
--
ALTER TABLE `document`
  ADD PRIMARY KEY (`id`),
  ADD KEY `FKinv0up4vmud0k3twcim8k3gii` (`id_doc_type`),
  ADD KEY `FK1u4rlvkuita670s9axjj6sc98` (`id_file`);

--
-- Contraintes pour les tables déchargées
--

--
-- Contraintes pour la table `document`
--
ALTER TABLE `document`
  ADD CONSTRAINT `FK1u4rlvkuita670s9axjj6sc98` FOREIGN KEY (`id_file`) REFERENCES `files` (`id`),
  ADD CONSTRAINT `FKinv0up4vmud0k3twcim8k3gii` FOREIGN KEY (`id_doc_type`) REFERENCES `document_type` (`id`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

标签: javamysqlspringhibernate

解决方案


推荐阅读