Spring AOP -to populate model data - spring-aop

Question 1:
Is it a good practice to use Spring AOP to populate\create the model in a portlet MVC environment? We have used Spring AOP extensively for populating\creating the Model object from an external source. Is AOP costly in-terms of performance when used very-extensively for such things as query execution, etc. I was informed AOP is good for crosscutting concerns and populating model data does not seem like a crosscutting concern, rather a main concern. I will be grateful for any guidance in this regard.
Question 2: I have a point-cut like so :
#Pointcut("execution(* getSomething(..))")
I have a class like so:
Class Aclass extends ASuper{
Somedata getSomething(String str){
super.getSomething(str);
}
}
The ASuper has the getSomething method as well, how many times the aspect for the point-cut will execute once or twice?
I am thinking twice but a bit confused here hence the question. Thanks for clarification.

Related

How to handle multiple entity update in the same transaction in Spring Data REST

Is anyone having an idea on how to handle multiple entity updates within the same transaction in Spring Data REST ? The same thing can be handle within Spring controller methods using the #Transactional annotation. If I am correct, Spring Data REST executes every execution event within separate transactions. So multiple entity updates cannot be handled in a proper way.
I am having issues updating 2 entities (ABC and PQR) within the same transaction and rolling back the ABC entity when the PQR entity is failed.
// ABC repository
#RepositoryRestResource
public interface ABCEntityRepository extends MongoRepository<ABC, String> {
}
// PQR repository
#RepositoryRestResource
public interface PQREntityRepository extends MongoRepository<PQR, String> {
}
// ABC repository handler
#RepositoryEventHandler
public class ABCEventHandler {
#Autowired
private PQREntityRepository pqrEntityRepository;
#HandleBeforeSave
public void handleABCBeforeSave(ABC abc) {
log.debug("before saving ABC...");
}
#HandleAfterSave
public void handleABCAfterSave(ABC abc) {
List<PQR> pqrList = pqrEntityRepository.findById(abc.getPqrId());
if (pqrList != null && !pqrList.isEmpty()) {
pqrList.forEach(pqr -> {
// update PQR objects
}
}
// expect to fail this transaction
pqrEntityRepository.saveAll(pqrList);
}
}
since #HandleAfterSave method is executed in a separate transaction, calling HandleAfterSave method means the ABC entity updation is already completed and cannot rollback, therefore. Any suggestion to handle this ?
Spring Data REST does not think in entities, it thinks in aggregates. Aggregate is a term coming from Domain-Driven Design that describes a group of entities for which certain business rules apply. Take an order along side its line items for example and a business rule that defines a minimum order value that needs to be reached.
The responsibility to govern constraints aligns with another aspect that involves aggregates in DDD which is that strong consistency should/can only be assumed for changes on an aggregate itself. Changes to multiple (different) aggregates should be expected to be eventually consistent. If you transfer that into technology, it's advisable to apply the means of strong consistency – read: transactions – to single aggregates only.
So there is no short answer to your question. The repository structure you show here virtually turns both ABCEntity and PQREntity into aggregates (as repositories only exist for aggregate roots). That means, OOTB Spring Data REST does not support updating them in a single transactional HTTP call.
That said, Spring Data REST allows the declaration of custom resources that can take responsibility of doing that. Similarly to what is shown here, you can simply add resources on additional routes to completely implement what you imagine yourself.
Spring Data REST is not designed to produce a full HTTP API out of the box. It's designed to implement certain REST API patterns that are commonly found in HTTP APIs and will very likely be part of your API. It's build to avoid you having to spend time on thinking about the straight-forward cases and only have to plug custom code for scenarios like the one you described, assuming what you plan to do here is a good idea in the first place. Very often requests like these result in the conclusion that the aggregate design needs a bit of rework.
PS: I saw you tagged that question with spring-data-mongodb. By default, Spring Data REST does not support MongoDB transactions because it doesn't need them. MongoDB document boundaries usually align with aggregate boundaries and updates to a single document are atomic within MongoDB anyway.
I'm not sure I understood your question correctly, but I'll give it a try.
I'd suggest to have a service with both Repositories autowired in, and a method annotated with #Transactional that updates everything you want.
This way, if the transaction fails anywhere inside the method, it will all rollback.
If this does not answer your question, please clarify and I'll try to help.

what is a target object in spring AOP

I am beginner to spring aop and i am going through spring aop documentation to understand the concepts but failed to understand 'target object'.
the documentation says target object is the "object being advised by one or more aspects. Also referred to as the advised object".
what is the meaning of being advised by one or more aspects here? can anyone explain me what is target object in Lyman terms as i am still a beginner.
For a simple explanation of some basic AOP terms please refer to my other answer. Please read that one first before continuing to read here.
So the target object is the (Java or Spring) component to which you want to add new behaviour, usually a cross-cutting concern, i.e. some behaviour that is to be applied to many classes in your code base.
An aspect is a class in which you implement that cross-cutting concern and also determine where and how to apply it. The where is defined by a pointcut, some kind of search expression finding the relevant parts of your code base to apply the behaviour to. The how is implemented in an aspect method called an advice.
So when we say that an aspect advises an object, it means that it adds (cross-cutting) behaviour to it without changing the class itself.
In Spring AOP this is mostly method interception, i.e. doing something before or after a method executes.
In the more powerful AspectJ you can also intercept changes of member variables and constructor execution. Furthermore you can change the class structure itself by adding new members or methods or making the target class implement an interface etc.
Is it possible to define multiple targets like below:
#Before(value = "com.test.createUpdateDeletePointCut() && (target(com.testlab.A) || target(com.testlab.B))")

Cakephp 3: Calling Table functions from Entity is a bad or good idea?

When I have some entity and I wanna save, validade or delete. Why do I have to call the Table method? For example:
$articlesTable = TableRegistry::get('Articles');
$article = $articlesTable->get(12);
$article->title = 'CakePHP is THE best PHP framework!';
$articlesTable->save($article);
Why isn't like this:
$article->save();
or $article->delete();
It's very simple to implement:
On my Article Entity I can do it like:
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity
{
public function save()
{
$table = TableRegistry::get($this->source());
$table->save($this);
}
}
It's working, but I would like to know if its a bad practice or a good idea.
Thanks in advance :)
TL;DR: Technically you can do it for the high price of tight coupling (which is considered bad practice).
Explanation: I wouldn't consider this best practice because the entity is supposed to be a dumb data object. It should not contain any business logic. Also usually it's not just a simple save call but there is some follow up logic to implement: Handle the success and failure of the save and act accordingly by updating the UI or sending a response. Also you effectively couple the entity with a specific table. You turn a dumb data object into an object that implements business logic.
Technically you can do it this way and I think there are frameworks or ORMs that do it this way but I'm not a fan of coupling things. I prefer to try to write code as lose coupled as possible. See also SoC.
Also I don't think you'll save any lines of code with your approach, you just move it to a different place. I don't see any benefit that would justify the introduction of coupling the entity to the business logic.
If you go your path I would implement that method as a trait or use a base entity class to inherit from to avoid repeating the code.

What exactly happens when i write Me.objectcontext in domain service?

I searched for the same question over the net for a long time and couldn't find any detailed answer. like this answer :-Gets the ObjectContext for this LinqToEntitiesDomainService(Of TContext).(from msdn).
So my question is
No 1:- exactly ObjectContext Property do in domainservice ?
NO 2:- Can i overloads the property ?
NO 3:- What will happen if i overloads the property ?
The question can be strange but i really want to what exactly happens when i write Me.object context in domain service?
ObjectContext represent your entity models entities and functions.
It provides some methods for running with entities as if they are objects.
You can't override this property. It is not virtual.
It has SaveChanges,'ExecuteFunction' like methods .
Beside this you may extendyour domain service's features by inheritance
public partial class DSrvMy : LinqToEntitiesDomainService<AHBSEntitiesMy>
You may code a class extends from LinqToEntitiesDomainService<AHBSEntitiesMy> it would be your OwnDomainService and then you can override Invoke , Query,Submit,.. like operations in it.
You were be code a layer in ria services.

Backbone Relational and subviews, best "save" strategy

I'm using Backbone-relational like this:
class window.Car extends Backbone.RelationalModel
class window.Person extends Backbone.RelationalModel
relations: [{
type: Backbone.HasOne
key: 'car'
relatedModel: Car
}]
There is also a PersonView, which embeds a subview CarView.
Now my question is, what is the best strategy when the user clicks "Save" in the PersonView? The problem is that the save will happen in two steps, first the car then the person. But what if validation fails with the person? It will cancel the save, but the car will be already saved!
Maybe Backbone-relational is not the best option here? Any alternative?
More generally, I'm more and more frustrated with Backbone playing not very nice with deeply embedded documents (I'm using MongoDB). Yes, the Todo app is nice, but the real world is more complex! Any guidance or tutorial would be very much appreciated.
It’s difficult to answer without to know the details, but, are you sure that you need relational models in the browser side?
Backbone is designed for restful applications. Is your API in the server side restful?
In your case (and without really understanding the constraints you have) I can think of the following implementation.
In the server the following URIs API:
[…]/carType/{carType}
[…]/persons/{person}
[…]/cars/{car}
In this implementation, “car” represents an actual physical object where “carType” represents a class of car. The backbone model for “car” contains the ID for the “carType” and the ID for the “person”. There are also backbone models for “carType” and “person”.
In this way, when you want to associate a “person” and a “carType” you create a new “car” and make a POST to the server. As “car” is its own independent object (and has its own URL), you can operate in a transactional way with it (that is what, I think, you are asking).
I hope it helps and the answer its not very far of what you are actually trying to do.
The best save strategy would be to save the whole thing atomically (in one step). Otherwise, you're always going to have these type of problems where failing to save one object on the server means you're going to have to destroy other objects on both the server and the client.
To support that, Backbone-relational has excellent support for serializing and deserializing nested objects.

Resources