Is it safe to use Spring Custom Events for trigger implementation - java

In a Spring based application I want to update some database (MySQL) tables whenever one table is updated. The logic is complex so I cannot depend on database triggers. I want to implement the logic in Java. I have the code to trigger functions. I came across Spring Custom Events and was considering using them to make the code more structured.
I was thinking whenever table1 is updated in a Repository instance it triggers an event which also updates another table. Right now inside a Repository I have an #Autowired repository for other database tables which need to be invoked manually. Can I get a more structured implementation logic?
The documentation says the events are synchronous. What is the order of invocation of event listeners invoked?
Can I end up in cycles? How do I prevent cycles? Any simple ideas.
Edit: I guess cycles will not be a problem as long as I do not publish another event in the listener.
As an aside I have an #Autowired entity manager instance in all the repositories. Are these entity manager instances all the same in all the Repositories? Here is the configuration file looks like.
Edit: I am asking this to understand if I need to persist all the objects to the same entity manager instance in order to be part of the same transaction. My entity manager instance is annotated #PersistenceContext. Am I correct in assuming that the entity manager has a singleton scope when declared using annotations.
Edit: Just in case it is helpful I have #Transactional annotation on all Repository classes.

Related

Cache options so #Postload annotated method dont get called everytime Hibernate is asked to retrieve object

I have a class annotated with JPA #Entity annotation, so objects of this class persist in database and are managed using Hibernate ORM. In my class constructor, a connection to a MQTT broker is created, so each object during initialization stablish a TCP connection.
When a object data is fetch from the database, this constructor can not be used by the ORM, as ORM uses default constructor without arguments, so I put the code that stablish the connection in a #PostLoad annotated method.
The problem is, everytime the web application page is refreshed the ORM is asked to get the object, and the #Postload method is executed so the TCP connection is stablished again... but I want the connection to be stablished only the first time object is fetch from database, and no everytime page is refreshed.
So the solution would be a ORM with in memory object cache. This way the first time object is loaded from database the #Postload method is called, but next times ORM is asked to retrieve the object it is retrieved from cache.
I dont know if this is possible with Hibernate, I have been playing with cache options and #Cacheable annotation but it seems that #Postload method is called everytime I use the findById method of Repository class, no matter the cache options I set. So I guess Hibernate cache is caching table rows, no objects in memory.
You could use an entity manager with an extended persistence context which spans multiple transactions, but I have no idea how or if Spring Data supports this. This way, the entity would not be reloaded from the database but be part of this extended persistence context. Note though, that this comes with other issues.
Usually, such expensive operations are simply not done in entities. You could move the logic out of the class, or do some kind of connection pooling/caching to avoid reconnects. I don't know why you need a dedicated connection, but connecting to message brokers is usually done differently. Usually, such connections are pooled by some context object of the library or maybe Spring offers some integration with options for pooling. In Java/Jakarta EE, this is usually done through resource adapters. I bet there is a JMS implementation for MQTT that you could use, probably also with Spring. AFAIK, in Spring Data JPA, you usually fire a domain/application event and react to that somewhere else. In that listener you could publish a message to a topic/queue through JMS or the native MQTT library.

Database synchronization techniques JPA / GUI

Good day everyone,I have Java application that use JPA (EclipseLink) for database access-some CRUD operation.How i can make synhronization in that case ? I mean if two users User1 and User2 start application on they machine and User1 change some records how to make User2 see it ? Is there some opportunity make User2 know that User1 change record and update only that record ?. The same problems has discussed here How to synchronize multiple clients with a shared database (JPA)?. Updated data (in Database) is not visible via JPA/Eclipselink
But the only what there suggest is to update by timer. Is it common way to do such things ?
Thank you for your help
[EDIT]
Monitor MySQL inserts from different application How to make a database listener with java? change notification on domain objects (Hibernate/Java)
Show me direction in resolving my problem .Hope can help somebody.
You should create a new entity Manager instance for each transaction. I suggest to use spring with a JTA Transaction manager and let the container manage the entity manager scope.
See http://spring.io/blog/2011/08/15/configuring-spring-and-jta-without-full-java-ee/
[edit]
Note that if there is a refreh(someEntity) method on the EntityManager, there is no refreshAll() method. This is because the EM is not designed to last a long time and be refreshed.
If you let the container (Spring is advised for a standalone app) manage the persistence context (container managed entityManager), it will instantiate a new EM for each transaction. In other words, each time you invoke a method annotated with #transactional annotation, a new EM will be instantiated for the lifecycle of the method.
In this case you don't need to take care about data synchronization, each time you want the grid to be refreshed you recall the transactional getMyEntityList() method which will retrieve a new fresh set of entities to display in the grid. You can of course use a timer to trigger the refresh.
The trick is to never let unpersisted modification in memory. Each time a user update the grid, open a new transaction and persist the modification, each time you refresh, retrieve a new up-to-date persistence context and let the GC dispose the old unreferenced entities.
If you don't want user1 to be able to override user2 data, configure optimistic locking.
Otherwise if you absolutely want to maintain an application scoped EM for performance reason (avoiding to regularly retrieve data for DB), you can set up a messaging topic for the different application instance to notify each others in case of data update, but this gonna lead to additional work and constraints.

JPA Entities Synchronization Mechanism

I'm writing an application (a CMS) using JPA/Hibernate, and in a single UI i have multiple components that might show the same entity (each one will show only a portion). I also have multiple UIs, in multiple sessions for multiple users.
Some of these components can also edit the entity, and all others component should always show the up-to-date entity.
A gross way would be a periodic refresh, but this is laggy and heavy, so i come up with a synchronization mechanism for jpa.
Using an interceptor (the hibernate one, since the jpa one is dumb) i can listen all the transactions, all the new/updated/removed entity and send notifications to every component interested in.
I also can catch derived transactions, meaning that if a component, responding to a notification, modify in any way the entity (opening a new transaction) i can resend the notification (only a delta).
This is becouse a component may modify the entity in a such way that another component may need to modify again it. (just a stupid example: a component set the birth date, and another re-calculate the age)
ps. The notifications are dispatched only after the transaction commit. This is mainly becouse
The section 3.5 of JPA specification states:
“In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context. A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.”
so the listeners would be useless if notified inside the transaction.
And (to grin and bear it) to group up modified entities and notify them all together.
This notification mechanism is growing complex, and i was wondering:
Why jpa has not such mechanism?
I'm inventing something strange?
How "real applications" solves this problem?

Tracking state change of an entity

I have a need to track he state change of a java entity class that uses MySQL as its database. I know the EntityManager has a mechanism to track state change for the entities it is managing. What I want is to access the entity state change. I want my application to fire an even to inform another application regarding the the new state of the entity. From what I gathered so far, there is no API that I can use to check the particular life-cycle an entity is in. Or is there?
Does any one have information on how to approach this?
JPA defines listener interfaces, that you can implement in order to be notified of lifecycle events for the entities.
Have a look at this article: http://www.objectdb.com/java/jpa/persistence/event
EclipseLink provides a set of events at the session level (SessionEventListener).
I assume you only want to notify of committed changes, after they have been committed? For this you can use the postCommitUnitOfWork event. The event/uow contain a UnitOfWorkChangeSet that contains the list of changes that were made in the transaction.

Creating a Publish-Subscribe Pattern to integrate to the DAO pattern

Based on the question (How to create a client notification service for a webapp or should I use an Observer Pattern?) I will like to know.
I have a fully implemented DAO with Entity beans containing only getters and setters method. Each entity is mapped to an EntityManager.
Currently there are no way of notifying users of any changes added/deleted/updated to a persistent storage such as a database.
I want to know, how will I implement the Publish-Subscribe pattern (also known as Observer pattern) such that I don't have to extend my current DAO architecture. I don't want my entities to inherit the Publisher because not all entities are update-able.
If there are any tools/frameworks/libraries that I can use for my situation, please let me know. Also, I'm not using any persistent framework at all (framework such as Hibernate), the DAO manager and Factory was completely written from scratch by me.
Regards,
I am building a similar concept... I don't care about all events and within projects we want to care about different events. So, we are building a pattern where all DAO operations are submitted to DROOLS Fusion and based on rules and some temporal reasoning, it notifies listeners via a notification architecture. Depending on your needs, the architecture could be simple listeners or JMS or email... whatever. If you have no criteria, just care about a callback for DAO events, then have your DAO insert, update, delete operations submit the object to listeners or some type of JMS queue.
Hope that was clear...
Paul
The first suggestion I would have is to embed an observable object within your DAO. Then you would have your subs look at this object (I've done similar things in the past).
The other suggestion I have is that you could add a trigger to the database itself. This would be especially useful if there is anything outside of your app that could change the DB that you want to notify your sub of.
Good luck.

Categories