[英]Javax Constraints: if field 'Type' is XXX then apply @NotNull annotation
I have a Spring Boot app with Postgres that has the following entity:我有一个带有 Postgres 的 Spring Boot 应用程序,它具有以下实体:
@Entity
@Table(name = "message")
public class Message {
public enum MessageType {
TEXT,
LOCATION,
IMAGE,
REPLY,
LIST,
BUTTON
}
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
@Column(nullable = false)
private MessageType type;
private String text;
@Embedded
private LocationRequest location;
@Embedded
private ImageRequest image;
@Embedded
private ContextRequest reply;
What I need to do is apply some given constraints depending on the value of the MessageType.我需要做的是根据 MessageType 的值应用一些给定的约束。 For Example, if
type
is equal to " LOCATION
", then I want to make sure all the fields of LocationRequest are required (ie not blank) Similarly, if instead the type is Image, I want that every field of ImageRequest is required.例如,如果
type
等于“ LOCATION
”,那么我想确保 LocationRequest 的所有字段都是必需的(即不是空白)。类似地,如果类型是 Image,我希望 ImageRequest 的每个字段都是必需的。
Can this be achieved with Javax Constraints?这可以通过 Javax 约束来实现吗? If not, are there other ways to achieve it, perhaps using Hibernate?
如果没有,是否有其他方法可以实现它,也许使用 Hibernate?
Since my colleagues may add a record to the DB directly with an INSERT, I need those constraints to be generated for the table and not for my app (I'm using Hibernate schema autogeneration feature, ddl-auto=true
).由于我的同事可能会使用 INSERT 直接向数据库添加记录,因此我需要为表而不是为我的应用程序生成这些约束(我正在使用 Hibernate 模式自动生成功能
ddl-auto=true
)。
You can do that with check constraints, although it is a bit cumbersome.您可以使用检查约束来做到这一点,尽管它有点麻烦。 Something like this:
像这样的东西:
@Entity
@Table(name = "message")
@org.hibernate.annotations.Check("case type when 'LOCATION' then location_col1 is not null and locatoin_col2 is not null when 'IMAGE' then image_col1 is not null else true end")
public class Message {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.