英文:
Trigger a Event in Java
问题
要识别实体对象中的修改属性。
如何将请求负载中的修改属性识别为实体对象,然后与表中的先前数值进行比较。
注意:我不想将每个属性与表字段进行比较,是否有一种方式可以将完整的实体对象与表字段进行比较。
英文:
Requirement is to identify the modified attribute in the Entity Object.
How to identify the modified attribute in the request payload as a entity object when compare against the data of the previous value in the table.
Note : I don't want to compare each attribute against the table field,is there a way where i can compare the complete Entity object against table field.
答案1
得分: 1
> 我不想逐个将每个属性与表字段进行比较
所以你不想要样板代码。
然后还剩下3个选项。
-
反射
使用Java反射来迭代(如果您的模型不是平面的,则需要递归)遍历您的成员变量并进行比较。当我有这个用例时,我从Spring的BeanCopy中复制了代码并进行了扩展。
-
使用字节码操作
a. 运行时字节码生成 - 在应用程序启动时使用bytebuddy/cglib/asm为您生成样板代码。
b. 编译时字节码生成 - 扩展Lombok以在应用程序编译时为您生成样板代码。
-
不要使用POJO,而是使用
Map<String,Object>
您将获得反射的灵活性,但显然会失去类型语言的好处。
还有一个选项,但这涉及将事件生成责任从应用程序代码移到数据库端。
-
CDC(变更数据捕获)
如果您使用支持更改数据传播的数据库,您可以将应用程序与此责任分离。
注意:
-
这是一个异步操作。
-
更改数据信息取决于您选择的数据库。旧值可能存在,也可能不存在。如果旧值不存在,那么需要另一种策略来找出发生了什么变化。
英文:
> I don't want to compare each attribute against the table field
So you don't want boilerplate.
Then there are 3 options left.
- Reflection
Use Java Reflection to iterate (need Recursion if your model is not flat) through your member variables and compare. When I had this usecase I copied code from spring's beancopy and extended it.
-
Use bytecode manipulation
a. Runtime bytecode generation - use bytebuddy/cglib/asm to generate the boilerplate for you, when the app starts up
b. Compiletime bytecode generation - Extend lombok to generate the boilerplate for you when your app compiles
-
Don't use POJO, instead use
Map<String,Object>
You will get the flexibility of reflection but obviously, you will loose the benefit of a typed language here.
There is one more option, but this involves moving the event generation responsibility from app code to Database side.
- CDC (Change Data Capture)
If you use a database that supports change data propagation, you can decouple your application from this responsibility.
The catch is,
-
This is an async operation
-
the change data information depends on the database you choose. Old value may or may not be there. If old value is not there, then it again needs another strategy to figure out what got changed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论