[英]Spring-data and Hibernate's auto-generated IDs
I'm using Spring-data's PagingAndSortingRepository
on my entities (having @GeneratedValue
IDs). 我在实体上使用Spring-data的PagingAndSortingRepository
(具有@GeneratedValue
ID)。 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))? 有什么办法可以使在有效负载中设置了ID的PUT和POST无法工作并引发异常,或者只是忽略提供的ID并使用Hibernate的ID(通过某些配置等),我知道我可以以编程方式对其进行检查(麻烦,嗯))?
The ability to provide IDs which will be used and persisted screws up the whole database. 提供将被使用并持续存在的ID的能力破坏了整个数据库。
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. 您没有说是否正在使用Spring MVC,但是假设您正在使用,则可以使用自定义数据绑定器来防止某些字段的绑定。
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-initbinder 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 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. 用@ControllerAdvice注释的类可以包含@ ExceptionHandler,@ InitBinder和@ModelAttribute注释的方法,并且这些方法将应用于所有控制器层次结构中的@RequestMapping方法,而不是在声明它们的控制器层次结构中。
eg 例如
@ControllerAdvice
public class BaseControllerAdvice {
@InitBinder()
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields(new String[] { "id", "version" });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.