简体   繁体   中英

Hibernate + Spring: Conditional on create bean validation

I use the date validaton using the @Future annotation.

@NotNull
@DateTimeFormat(pattern="yyyy-MM-dd")
@Column(name = "FROM")
@Temporal(TemporalType.DATE)
@Future
private Date from;

@NotNull
@Column(name = "FOO")
private String foo;

I perform CRUD operations using Rest API. The requirement is the from date will be in future - after the entity is being created (today). However, the time changes and in case of changing the field foo using ex. PUT method, the validation won't pass.

@PutMapping(value = "/{id}")
public ResponseEntity<?> put(
    @Valid @RequestBody MyEntity myEntity, 
    @PathVariable("id") int id) 
{
    ... update entity based on id
}

When I call this method in the far future (after the from value persisted), the validation doesn't let me perform the operation, because the field from is no more valid.

There is a simple in-built solution to trigger a certain validation only on create event?

I have been thinking over creating the own cross-field validation through annotation, however I am not able to determine the creation based on other fields.

You can use Grouping Constraints , to restrict which validation set to use for: pre-persist , pre-update , pre-remove and ddl (For database schema).

So to validate from field just for persist operation and ignore it for put(update), you may:

Add an interface eg GroupFuture :

package com.example.entity;

public interface GroupFuture {}

In your MyEntity , I think you should also add @NotNull constraint as @Future consider null as valid value:

//...
//Maybe @NotNull
@Future(groups = GroupFuture.class)
private Date from;

//...

Finally, if you've configured hibernate using: persistence.xml , add this line in the persistence-unit setting:

<property name="javax.persistence.validation.group.pre-persist" value="javax.validation.groups.Default, com.example.GroupFuture">

Programmatically:

// If you're using pure hibernate
Configuration configuration = new Configuration().setProperty("javax.persistence.validation.group.pre-persist", javax.validation.groups.Default, com.example.GroupFuture);

`

// If you're using JPA/hibernate
entityManagerFactory.getJpaPropertyMap().put("javax.persistence.validation.group.pre-persist", javax.validation.groups.Default, com.example.GroupFuture);

Useful reading(even it's for hibernate 3.6): Chapter 23. Additional modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM