简体   繁体   中英

Spring-data and Hibernate's auto-generated IDs

I'm using Spring-data's PagingAndSortingRepository on my entities (having @GeneratedValue IDs). Is there any way so that PUT and POST with the IDs set in the payload either won't work and throw an exception or just ignore the provided ID and use Hibernate's (via some configuration, etc., I know I can programatically check for it (cumbersome, meh))?

The ability to provide IDs which will be used and persisted screws up the whole database.

Thanks!

You do not say if you are using Spring MVC but assuming you are then you can use a custom data binder to prevent binding of certain fields.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-initbinder

You can apply this on a global level via a Controller Advice:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-controller-advice

Classes annotated with @ControllerAdvice can contain @ExceptionHandler, @InitBinder, and @ModelAttribute annotated methods, and these methods will apply to @RequestMapping methods across all controller hierarchies as opposed to the controller hierarchy within which they are declared.

eg

@ControllerAdvice
public class BaseControllerAdvice {

    @InitBinder()
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields(new String[] { "id", "version" });
    }
}

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