Do axon state-based aggregates have a way of specifying #CreatedDate and #LastModifiedDate? - axon

When creating an Axon JPA state-based aggregate is there a way to mark certain fields as being the #CreatedDate and #LastModifiedDate (as is possible with spring data jpa)?
In other words does Axon have the functionality where if any state of the aggregate is changed then axon automatically updates the #LastModifiedDate without us having to repeat it in every #CommandHandler?

Try using #CommandHandlerInterceptor inside your aggregate to intercept all commands and set
lastModifiedDate field.
#CommandHandlerInterceptor
public Object intercept(Object myCommand, InterceptorChain interceptorChain) throws Exception {
this.lastModifiedDate = Instant.now();
return interceptorChain.proceed();
}

I believe the proper solution would be to implement Axon's HandlerEnhancerDefinition interface to update these fields. This way you can grab the same timestamp (Instant) from the event that gets persisted in the event store and use that on your state-stored aggregate to make them match.
I wrote a blog post with a working example with a detailed explaination how to do this: https://michael.jeszenka.com/automatically-updating-timestamp-fields-for-axon-state-stored-aggregates/
Essentially, you will need to implement the wrapHandler() method to specify which types of event handlers you want to wrap with your enhancer. Then you will need to define a wrapper class to execute your desired behavior, which in our case is automatically handling the timestamps of the state-stored aggregate. This wrapper class will need to implement the Object handle(Message<?> message, T target) method which will allow us to grab the event timestamp from the meta data and use it to set the state-stored aggregate fields.

Related

How to track Linq2Db add,update,delete events?

How can I track events on adding, updating or deleting entity rows with Linq2Db?
I need to recalculate some data in db on this operations, what is the best way?
On Entity Framework I use my custom Repository class with custom Add operations. Mabe this is only way in Linq2Db, but I am interesing, mabe there is some catcher to notify this events?
It is not so easy as in EF, because linq2db manipulates with SQL and you can easily update thousands records by single update statement.
For example
db.SomeEntities.Where(e => e.IsExpired)
.Set(e => e.ExpirationDate, e => Sql.CurrentTimestamp)
.Update();
The same technique can be used with insert from, update from, delete.
But there is possibility to catch SQL AST before executing. You have to override ProcessQuery method in your DataConnection class.
Sample is here: ConcurrencyCheckTests.cs
You should return the same statement that is passed to method but with changed property statement.IsParameterDependent = true to prevent query caching.
SqlStatement analysis is not trivial task but possible. You have to handle SqlUpdateStatement, SqlInsertStatement, SqlDeleteStatement, SqlInsertOrUpdateStatement.
Second option is to write your own extensions which manipulates with single objects, for example, UpdateTracked(), DeleteTracked(), etc. But as you can see from first example it will not help in complex queries.

Modify JSON during entity denormalisation

During normalisation of JSON, I am able to modify the entities as they are processed. Say, for example, I add a new property to entities during this phase. I can do this by setting a function for processStrategy.
What I was wondering was: is there any way to do similar custom processing during the denormalisation phase, as each entity is denormalised?
There is not a way to do that during denormalization. The expectation is that you run your processing once during normalization so you won't have to do it again.

Adding a callback when reading from an object in Twig

Let's say I have a basic entity called Entity which is mapped to a database table. This entity has got two properties: propertyA and propertyB.
One particularity of this entity is, although we may store whatever we want in these properties, when using the value of propertyB on a Twig template with entity.propertyB we want to systematically truncate the value to 100 characters.
Now, this is perfectly doable in several ways:
Truncate the value directly in the getPropertyB() method;
Register a Twig extension and create a dedicated filter;
Add a lifecycle callback on the entity to truncate the value before the object is actually created.
As this is strictly a display rule, and not a business rule on our entity, the second solution seems to be the best IMHO. However, it demands we apply the filter every time we need to use the value of propertyB in a template. Should an unaware developer come by, the value may not be truncated.
So my question is: is there a way to register some kind of callback, strictly restricted to the view model wrapping our entity, which would allow us to apply some filters on the fly on some of its properties ?
Since you never need to access anything beyond 100 characters, you can truncate the property in its setter. This doesn't really pollute Entity code, because this is some logic inherent to it.

Does Spring MVC require copy/paste of Entity to FormObject?

I'm developing my first Spring 3 webapp. In Spring 2, we used to have formBackingObject load data from the database, then let Spring binding update some of the fields, and then onSubmit would persist those changes.
In Spring 3 it seems I have two options:
Let the user edit 100% of the persistent object. This would mean that the object's ID would need to be a hidden field
Create a form object which holds the editable data, and then map that onto the persistent object on submit
The first option is not truly an option, we cannot let the user edit all fields, and we'd rather not present data in hidden fields where anyone capable of pressing F12 can alter the values.
The second option seems like a decent design approach. However, it appears that it requires to essentially clone every editable, persistent class.
#Entity
public class Company {
private String uuid; // not editable!
.. 30 other properties, 2 are not editable
}
public class CompanyForm {
.. 28 of above properties
}
and then some mapping mechanism with lots of
public void map(CompanyForm cf, Company c) {
cf.setName(c.getName());
.. 27 other set(get())
}
I'm praying this is not the "as designed" approach of Spring's MVC binding. However, all tutorial I've found so far are terribly trivial and implement option 1 from above. Does anyone have some suggestions for implementing option 2?
Thanks, Simon
DataBinder API
Note that there are potential security implications in failing to set an array of allowed fields. In the case of HTTP form POST data for example, malicious clients can attempt to subvert an application by supplying values for fields or properties that do not exist on the form. In some cases this could lead to illegal data being set on command objects or their nested objects. For this reason, it is highly recommended to specify the allowedFields property on the DataBinder.
You can use it together with option 1
A pragmatic way would be to just ignore the non editable fields on the update statement.
I have actually circumvented this in the past by using a #ModelAttribute annotation and detecting the PK on the request, if you do it this way Spring will use the object that is returned from #ModelAttribute and automatically copy the submitted object to it.
It's kind of a hack and not obvious to someone who comes in to maintain the code though.

Symfony2: best approach to use business (repository) logic in entity or controller

I'm having a design issue in my project, related to where put some business logic.
I have three entities, Event, TicketOrder and Ticket. One Event has a lot of TicketOrders and one TicketOrder has a lot of Tickets.
In my template, I have to show how many tickets an Event has. I've thinking of the best approach to achieve this and didn't get a good solution. I've tried this:
1) Create a private member 'ticketsCount' in Event entity, with setTicketsCount and getTicketsCount method. Create a 'loadTicketsCount' method with a LifeCycleCallback 'PostLoad', to access the TicketRepository method 'findByEvent'. This was impossible because I can't access repository in an entity class.
2) In the action that will be used to display the Event, I can access Ticket Repository and set event 'ticketsCount' property manually. I don't know if it is a good approach because if my action is listing a lot of events I'll have to loop trough all events and make a repository call to each of then.
I really don't know the best approach to achieve this and will really appreciate if someone can help me.
Thanks! ;)
When you use findAll, findBy or findBy* methods of doctrine entity repository, a simple php array is returned containing the entity objects.
The array class implements countable interface. So using twigs length filter
{{ ticketOrder.tickets|length }}
you perform a simple php count() on the array.
Actually it makes now sense to perform a count query, because you already have the result in memory. So it seems more efficient to count the result and retrieve it from memory, because when you access associations they are completely loaded into memory.
However associations between entities can get pretty large. So imagine you have associations with hundred thousands of entities. You won't those entites to be loaded all together and kept in memory all the time. So in Doctrine 2.1 you can annotate an association as Extra Lazy. If you do so in your case a count query is performed when you call the above twig filter. But the result is not kept in memory.
http://docs.doctrine-project.org/en/2.0.x/tutorials/extra-lazy-associations.html
According to your latest comment:
I can imagine one way to do this. In a template you can call a controller's action with the render statement like
{% render YourMainBundle:getTickets with { 'event_id' : event.id } %}
and in this action you can call a query that looks for all tickets associated to the certain event. This action has to return html, e.g. an template filled with data.

Resources