gpt4 book ai didi

mysql - 为什么在添加列时所有行都获得空值?

转载 作者:行者123 更新时间:2023-11-30 21:35:31 25 4
gpt4 key购买 nike

我正在尝试向现有表中添加一个新列。预期为 UNKNOWN,而不是所有行都获得空值。请帮忙。这是我的代码。

成绩.kt

package com.example.demo.model

import javax.persistence.*

@Entity
class Grade {
@GeneratedValue
@Id
var id: Long? = null
var grade: Int? = null
var name: String? = null
var enabled: Boolean = false
@Enumerated(EnumType.STRING)
var studentStatus: StudentStatus = StudentStatus.UNKNOWN

}

首先我创建了这个没有 studentStatus 的表。现在我想将 studentStatus var 添加到表中,我发现我必须在 Gradle.kt 中将其声明为 StudentStatus.UNKNOW,但它变为空。

StudentStatus.kt

package com.example.demo.model

enum class StudentStatus{
PASS,
FAIL,
UNKNOWN
}

GradleRepository.kt

package com.example.demo.repository

import com.example.demo.model.Grade
import org.springframework.data.repository.CrudRepository

interface GradeRepository : CrudRepository<Grade, Long>

构建.gradle

buildscript {
ext {
kotlinVersion = '1.2.71'
springBootVersion = '2.1.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
classpath("org.jetbrains.kotlin:kotlin-noarg:${kotlinVersion}")
}
}

apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'kotlin-jpa'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin {
kotlinOptions {
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"
}
}
compileTestKotlin {
kotlinOptions {
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"
}
}

repositories {
mavenCentral()
}


dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.springframework.boot:spring-boot-starter-mustache')
implementation('org.springframework.boot:spring-boot-starter-web')
implementation('com.fasterxml.jackson.module:jackson-module-kotlin')
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly('com.h2database:h2')
runtimeOnly('mysql:mysql-connector-java')
testImplementation('org.springframework.boot:spring-boot-starter-test')
}

最佳答案

当您在类上定义附加属性时,Hibernate 可以将新列添加到现有表中。但是 Hibernate 不会自动迁移现有的值/行。

对于这种情况,您应该使用像Liquibase 这样的数据库迁移工具。或 Flyway . Spring Boot supports both .这些工具可帮助您编写一个迁移,该迁移会在下一个应用程序启动时被激活,并使用缺失值更新数据库中的现有条目。

我假设您只对现有值有问题,因为定义的默认值对于新插入的值看起来是正确的。

关于mysql - 为什么在添加列时所有行都获得空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54042392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com