如何向需要查询实体以执行验证的JPA实体添加验证(how to add validation to JPA Entities where it requires to query the entity

系统教程 行业动态 更新时间:2024-06-14 17:02:18
如何向需要查询实体以执行验证的JPA实体添加验证(how to add validation to JPA Entities where it requires to query the entity to perform validation)

假设我有以下实体:

@Entity public class MyModel { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Integer counter; private Integer someVal; }

我想在这个实体上有CRUD操作和一些其他方法,因此我有一个存储库,如

@Repository public interface MyModelRepository extends JpaRepository<MyModel, Long> {}

问题:我想在保存时添加某些验证,我需要查询模型。

例如:在保存时,检查someVal的值是否大于MyModel的someVal,其计数器比当前保存对象少一个。

PS:它也可以是跨实体验证。 PS:我仍然需要使用JpaRepository生成的自动crud。

否则,我将实现DAO并编写自定义实现,然后将其映射到RestController。

我理想地想要的是定制一些部分,同时保持其余的魔力。

Suppose I've following entity:

@Entity public class MyModel { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Integer counter; private Integer someVal; }

I want to have CRUD operations and some additional methods on this Entity, hence I have a repository such as

@Repository public interface MyModelRepository extends JpaRepository<MyModel, Long> {}

Question: I want to add certain validations on save, where I need to query the models.

Eg: on save, check the value of someVal is greater than the someVal of MyModel whose counter is one less than currently saving object.

PS: It could be cross Entity validations as well. PS: I still need to use automatic crud generated by JpaRepository.

Otherwise, I've to implement DAO and write custom implementations and then map it to RestController.

What I would ideally want is customization of some parts while keeping rest of the magic.

最满意答案

如果有人想知道,我是如何解决它的:

方法1:原始方式

@RestController public class MyModelController { // autowired MyModelRepository & other models repositories @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) public long save(MyModel model){ // added validation here (which involves queries to both repositories // returned saved entity.id or failed with 0 } }

方法2:

显然,问题是关于更好的方法。 正如@Alan Hay建议使用Validator ,但仍然使用Controller。 如果没有控制器覆盖,如何将Validator绑定到Repository文档不清楚。

public class MyModelValidator implements Validator{ // Autowired MyModel repository and others // override both supports() and validate() // PS: moved validation logic from Controller in method 1 to validate() }

现在将控制器更改为:

@RestController public class MyModelController { // autowired MyModelRepository & other models repositories // autowire MyModelValidator as mymodelValidator @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) public long save(@ModelAttribute("myModel") MyModel model, BindingResult result){ mymodelValidator.validate(model, result); if(result.hasErrors()){ // return 0 } // save & return saved entity's id } }

方法3:最后如何完成。

@SpringBootApplication public class MyApplication extends RepositoryRestConfigurerAdapter{ public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Override public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) { validatingListener.addValidator("beforeCreate", new MyModelValidator()); validatingListener.addValidator("beforeSave", new MyModelValidator()); } }

In case someone wonder, how I solved it:

Method 1: Original way

@RestController public class MyModelController { // autowired MyModelRepository & other models repositories @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) public long save(MyModel model){ // added validation here (which involves queries to both repositories // returned saved entity.id or failed with 0 } }

Method 2:

Obviously, question was about a better approach. As @Alan Hay suggested using Validator, but still with Controller. Document was not clear on how to bind the Validator to Repository without a controller override.

public class MyModelValidator implements Validator{ // Autowired MyModel repository and others // override both supports() and validate() // PS: moved validation logic from Controller in method 1 to validate() }

Now changed the controller as:

@RestController public class MyModelController { // autowired MyModelRepository & other models repositories // autowire MyModelValidator as mymodelValidator @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) public long save(@ModelAttribute("myModel") MyModel model, BindingResult result){ mymodelValidator.validate(model, result); if(result.hasErrors()){ // return 0 } // save & return saved entity's id } }

Method 3: How it is done, finally.

@SpringBootApplication public class MyApplication extends RepositoryRestConfigurerAdapter{ public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Override public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) { validatingListener.addValidator("beforeCreate", new MyModelValidator()); validatingListener.addValidator("beforeSave", new MyModelValidator()); } }

更多推荐

本文发布于:2023-04-21 18:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/efdd432b86b15478c272e0f05596e041.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   add   validation   Entities   JPA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!