Spring Boot REST · @Constraint for delete?

2020-04-20 21:11发布

I'm working on a system's back end that uses Spring Boot, REST, HATEOAS, Hibernate and PostgreSQL. For validation, I started using classes that extend org.springframework.validation.Validator. It works well, but only for calls made by the front end. For calls made in the back end, such as by using EntityManager, they don't fire. I've managed to have another validator being called in this situation by using @Constraint for ElementType.TYPE, but it only gets called for create and save methods.

Is it possible to use this validator to validate on delete methods too? There's a project here that's a non operational subset of the project I'm working on, containing the validators I mentioned.

Thanks in advance.

P.S.: I'd rather avoid manually calling the validators whenever I call a repository method in the back end.

P.P.S.: This answer makes me believe it's possible, but I couldn't translate the XML configuration to JavaConfig.

1条回答
够拽才男人
2楼-- · 2020-04-20 21:43

I finally found the answer. In application.properties, add:

spring.jpa.properties.javax.persistence.validation.group.pre-remove=javax.validation.groups.Default

The linked question told me which property I needed, but I didn't know where to place it. I tried to use custom Java configuration and even persistence.xml configuration, but several other things failed.

Here, I learned that "[...] all properties in spring.jpa.properties.* are passed through as normal JPA properties (with the prefix stripped) when the local EntityManagerFactory is created." So I just added that prefix and it worked.

查看更多
登录 后发表回答