gpt4 book ai didi

java - 将具体类对象持久化到数据库时,将抽象类中的字段设置为强制字段

转载 作者:行者123 更新时间:2023-12-01 17:01:17 33 4
gpt4 key购买 nike

public abstract class Parent{
@NotNull
private String appId;
}

@Documnet
public class child1 extends Parent{
@Id
private String id;
...more fields
...getters setters
}

@Documnet
public class child2 extends Parent{
@Id
private String id;
...more fields
...getters setters
}

我想确保每次在 mongodb appId 字段中保留 Child1 或 Child2 时都有一个有效值,否则我希望我的代码抛出一些异常或错误。

我不想每次 appId 有值时都显式检查。它应该是一次性的事情,您只需配置一次,它就会反射(reflect)在扩展 Parent 的每个类中

我使用 spring-boot 和 mongodb 作为数据库。

ependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.0.1'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'

testImplementation 'org.springframework.boot:spring-boot-starter-test'

compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.2.6.RELEASE'
compile('org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.6.RELEASE')
compile('org.glassfish.jaxb:jaxb-runtime:2.3.1')

compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
}

最佳答案

这是我解决这个问题的方法,不确定这是否是一个具体的解决方案

public abstract class Parent {
@NotNull
private String appId;
}

@Document
public class Child extends Parent{

@Id
private String id;

}

ValidatingMongoEventListenerLocalValidatorFactoryBean创建bean

@Configuration
public class SomeClass {

@Bean
public ValidatingMongoEventListener createValidatingMongoEventListenerBean(LocalValidatorFactoryBean localValidatorFactoryBean){
return new ValidatingMongoEventListener(localValidatorFactoryBean);
}

@Bean
public LocalValidatorFactoryBean createLocalValidatorFactoryBean(){
return new LocalValidatorFactoryBean();
}

}

现在,如果我们尝试在没有 appId 的情况下保留扩展 Parent 类的 Child 类,它将抛出 ConstraintViolationException

关于java - 将具体类对象持久化到数据库时,将抽象类中的字段设置为强制字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61503527/

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