I would like to know if there is a way —maybe with AOP— to extend table/entity definitions so that I can add functionality across the board that requires persistence.
Let me explain what I want to do with a concrete example. Let's suppose we have a simple ecommerce system:
Now, let's suppose that we think:
hey, wouldn't it be great if we could add a field to timestamp all entities?
You would now know things like:
- When a User registered
- When an item was created
- When a shopping cart was created
- When an item was added to a shopping cart
- When an order was placed
- When was the order was processed and paid
Now you have another great idea:
What if there was a status field for all entities so I could soft-delete or archive items, etc.
And yet another idea:
What if there was a text field called
metato serialize unimportant data, but that could help adding functionality without painful database modifications.
There are solutions I can think of (meeting relational integrity requirement):
Of course, you would need to go back, change your tables, modify your implementations so that when creating/updated you save the
timestampof then operation, same for
status, same for
And a somewhat convoluted but very modular way. Create some sort of plugin, that creates a table that handles the field, and 1 pivot for each entity. And through events, associate the extended data to the existing entities accordingly.
But what if... you could just tell Hibernate to extend the table definitions programmatically at run time, and add the persistence behaviors through something like AOP to inject functionality.
I actually did the first thing (programmatically extending table definitions outside existing implementation) in Doctrine successfully once, but I'm just starting to learn Hibernate. OTOH, I'm just starting to learn Spring and know the basics on AOP, so at least in my mind it is feasible to intercept Hibernate's configuration process where it understands table definitions.
So, is this possible with Spring and Hibernate?, how?, can you provide an example?
Addendum: The problem is that I need to do this more than once, and it could come from anywhere. AOP was my answer to the multiple inheritance problem since extending classes would be too constrained, however, in the past I did it with Events and worked just as fine... IIRC the problem is that I had to hack Doctrine in order to do this to fire an event at the time between when the model description was being converted from configuration files into actual models.
AOP is not a must, just an idea for an approach if such an event or dependency injection mechanism is not already in place. Another approach could be mixins, but I come back to AOP as probably the most elegant solution.
The main requirement here is to not modify the original model's code.
Disclaimer: I'm not an expert on AOP but I'm fairly familiar to the concepts.