Is is possible to attach EntityProxy to another RequestContext ? And should I? - gwt

I have a little form that edits my entity. I create that entity using one instance of RequestContext and then in handler of "save" button I'm trying to persist it using another instance of RequestContext.
Attempt to persist fails with expected exception: java.lang.IllegalArgumentException: Attempting to edit an EntityProxy previously edited by another RequestContext
The questions are:
Is is possible to attach EntityProxy to another RequestContext ?
Is it right thing to do ? Or I should reuse one RequestContext saving it
as property of my class ?

Reuse the existing one. If you need a new one, merge them. But it really doesn't make sense to make a new one. Here's why:
When you make a RF call to the server, it goes through several steps, as it is geared mostly toward how to read and persist entities, and the various value properties they work with.
Create or retrieve any of the instances to be dealt with
Apply setters to these instances, new or existing, and validate them
Run the service invocations, either as methods invoked on the entities, static calls, or service calls.
These three steps are done in this order to ensure that the object modified and then passed to a service call makes sense when it gets there. Future calls (i.e. other requests) then probably do not need to make those same changes to the same entities, and if they do, then they need to make the changes themselves.
A given RequestContext consists of all of these things then. If you had two requests, and one represented the setters to be called (the edits from the form) and the other the service request, firing one means only calling the setters, but not the service call to save it, while firing the other means only call save without the service call.
After an EntityProxy has been marked as being edited by one request context, attempting to use it in another one is almost certainly an error, so the exception you are seeing is thrown. Use the existing one, or use RequestContext.append if needed to switch to a new RequestContext type to actually run the save operation.
RequestFactory isn't RPC - your objects aren't just Java Beans, but are proxies (either EntityProxy or ValueProxy) of some server object, and requests are used to manipulate them asynchronously.

Related

Should a GWT RequestFactory Locator method expect a passed-in JPA entity to be attached or detached?

Right now I have to call JPA merge() at the end of my service method to persist changes. I'm doing this because our servlets do not start a transaction before the Locator.find() runs. They start them later in the service method.
I know that RequestFactory uses my Locator find() and updates the object based on what the client sent to the server, so I was just wondering if maybe that object should be an attached object and therefore allow JPA to handle the changes "naturally" rather than explicitly call merge().
Or perhaps this just depends on the situation?
I don't know JPA much, but I confirm that you SHOULD scope your transactions to your service methods: a RequestContext is a batch of requests that can each succeed or fail independently, putting them all in a single transactions would violates that principle. There are also cases where your Localor#find can be called, changes applied to the entity, but then the entity is never passed to any service method: you wouldn't want the changes to be persisted in this case.

What happens first - Symfony2 persist

I have been wondering what happens first with symfony2 regarding persistence of entities.
Let's say for example I have a function in my controller which is called when persisting data but also I have a lifecycle call back which runs PrePersist. Which function is run first?
Also if I wish to perform some sort of calculation based on user submitted values (from a form) is it better to do this from within the controller or from within the entity its self, again with a PrePersist callback?
The latin prefix pre means “before”. ;) Therefore the PrePersist callback will be applied before persisting.
If you call some functionality on persisting, it depends if the $EntityManager->persist() is before or after that. The LifecycleCallback is “atomic” with the persist operation. In detail, this means that your LifecycleCallback is applied before the UnitOfWork computes the modifications which should be written to the DB.
You should also keep in mind that nothing is written to the DB before you call $EntityManager->flush().
As for the calculation: There's no hard rule, but as a rule of thumb:
If all logic required is available in the context of the entity, and components outside the entity don't need to know about a transformation of the passed value, you can do it inside a getter/setter of the entity.
As soon as outside components are affected, or you need external services for the modification, you should definitely do it inside a controller or a dedicated management service.

com.google.web.bindery.requestfactory.shared.Locator.getVersion() - What is this method used for?

I'm writing my first GWT-Application and need your advice. I have no problems implementing a locator for database entities where I can reuse the version-column used for optimistic locking by hibernate, but one of my entities represents a ldap-Object. Can you tell me what the method getVersion() of the Locator is used for and how I can implement this method for my ldap-Object? I will do read and write ldap objects.
From GWT documentation, getVersion method is
Used by RequestFactory to infer if an entity has changed. The backing store (JDO, JPA, etc.) is responsible for updating the version each time the object is persisted, and RequestFactory calls getVersion() to learn of changes. This information is used in two places. First, the RequestFactoryServlet sends an UPDATE event to the client if an entity changes as a result of the method invocation on the server, for example, when a call to persist an editable entity results in an updated version on the server. Second, the client maintains a version cache of recently seen entities. Whenever it sees an entity whose version has changed, it fires UPDATE events on the event bus so that listeners can update the view.
Since many persistence frameworks offer generic find/get/query methods, it's also possible to create a generic Locator class and specify it in the #ProxyFor annotation for each entity type. To do this, all your entities can extend a base class that provides getId() and getVersion(). Alternatively, the generic Locator can use reflection to call getId() and getVersion() when needed.
Not sure if you're looking for anything else in addition to this.
I have the same problem. My first thought was to use the Attribute modifyTimestamp and createTimestamp. But there is still a functional gap:
The smallest unit of These timestamps is seconds so a Change in the same second can not be detected. Another solution would be to use a kind of checksum over all attributes of the ldap object. Not very nice..

What is the correct way to manage dependency injection for Entity Framework ObjectContext in ASP.NET MVC controllers?

In my MVC controllers, I'm using an IoC container (Ninject), but am not sure how to best use when it comes to the Entity Framework ObjectContext.
Currently, I'm doing something like:
using(var context = new MyObjectContext())
{
var stuff = m_repository.GetStuff(context);
}
This is the best way to manage from the point of view of keeping the database connection open for the shortest time possible.
If I were to create the ObjectContext via Ninject on a per request basis, this obviously keeps the database connection open for too long.
Also the above code would become...
var stuff = m_repository.GetStuff(m_myObjectContext);
(And when would I dispose of the context...?)
Should I be creating a factory for the ObjectContext and pass that in via DI? This would loosen the coupling, but does this really help with testability if there is no easy means of maintaining an interface for the ObjectContext (that I know of)?.
Is there a better way? Thanks
This is the best way to manage from the point of view of keeping the
database connection open for the shortest time possible.
If I were to create the ObjectContext via Ninject on a per request
basis, this obviously keeps the database connection open for too long.
Entity Framework will close the connection directly after the execution of each query (except when supplying an open connection from the outside), so your argument for doing things like this does not hold.
In the past I used to have by business logic (my command handlers to be precise) have control over the context (create, commit, and dispose it), but the downside is that you need to pass on this context to all other methods and all dependencies. When the application logic gets more complex, this results in less readable, less maintainable code.
For that reason I moved to a model where the unit of work (your MyObjectContext) is created, committed, and disposed outside the control of the business logic. This allows you to inject the unit of work into all dependencies and reuse the same unit of work for all objects. Downside is that this makes your DI configuration a bit harder. Some things your need to make sure of:
The unit of work must be created as per web request or within a certain scope.
The unit of work must be disposed at the end of the request or scope (although it is probably not a problem when the DbContext is not disposed, since the underlighing connection is closed and DbContext does not implemente a finalizer).
You need to explicitly commit the unit of work, but you can't do this at the end of the web request, since at that point you have no idea whether it is safe to commit (since you don't want to commit when your business logic threw an exception, but at the end of the request there is no way to correctly detect if this actually happened).
One tip I can give you is to model the business logic in the system around command handlers, since this allows you do define a single decorator that handles the transactional behavior (committing the unit of work and perhaps even running everything in a database transaction) at a single point. This decorator can be wrapped around each handler in the system.
I must admit that I have no idea how to register generic types and generic decorators with Ninject, but you'll probably get an answer quickly when asking here at Stackoverflow.

UpdateOrAdd method in Repository + UnitOfWork pattern

Is it acceptable to add UpdateOrAdd method in Repository pattern or maybe UpdateMethod with parameter 'AddIfNoExists' ?
I want to add such method to simplify using od DataServices.
For example: Client code show data in grid..then client sends all data to UpdateMethod of repository..then Repository figures out what data was added and what data was modified.
It is completely up to you how will the public interface of your repository look like. If you want single method for both inserting and updating you can of course expose it but you must correctly handle the behavior in method implementation - EF will not help you with it because it expects separate calls for inserts and updates.
I always create one method in the repository which called Add, it will add new object if it's new and will update the object if it's existing but saving or updating this not belong to the repository because the repository didn’t track state and which one new or which one existing before, this is belong to the Unit of work, this why the Unit of work pattern telling that you should track of what you've changed; otherwise, that data won't be written back into the database
So you will need to add this method in the unit of work class depending on your ORM or you DAL approach
So the Unit of work will track
New objects
Dirty objects
Delete object
And at the end you will
Commit (Save)--> add new and update existing or
Rollback