Docs state obvious thing:
a method will throw an exception if it is executed inside existent transaction.
Can anyone give a meaningful example of when/why it can be used on purpose?
Well, there may be several use cases that require your code not to run in a transaction. You'd use NEVER to enforce that as opposed to NOT_SUPPORTED which would just "suspend" the current transaction and resume it afterwards.
One use case that we had would be sending an email after some transactional operation. Sending the email itself doesn't require a transaction and to make sure the operation was successful and didn't get rolled back at the last moment our email sending service uses NEVER (otherwise we might accidentally send a "success" email and then get a rollback). That way if someone would call it while the operation's transaction still hasn't been successfully committed yet we'd get an exception and know that this should be fixed.
One use case might be framework related code that handles transactions or scopes. Think of Apache Deltaspike, arquillian, hibernate, ...
If you expose public methods you might want to make sure they are not wrongly used inside some transaction. Instead of unintentionally messing up open transactions you would rather fail-fast using #NEVER.
If you want to modify a nontransactional resource inside your code and want to make sure that others know this fact, you can use this feature.
Related
http://activemq.apache.org/hello-world.html
In the above link author suggest to try transactional sessions, but unfortunately after lots of search on internet not able to get what transactional sessions mean.
And what are its pre-requisite??
The links that i read are:
http://activemq.apache.org/how-do-transactions-work.html
http://activemq.apache.org/should-i-use-transactions.html
Unfortunately still not able to get the meaning and particularly implementation of transactional session and why to use it.
Can any one provide sample reference implementation or tutorial for same. ?
Unfortunately still not able to get the meaning and particularly implementation of transactional session and why to use it.
Its simple if you want to perform an operation on a message , you received a message and did operation if the output is not correct , you dont want to proceed.
let me check for implementation will send if I find on my previous project
I'm using Hibernate and Spring and I'm currently stuck with something which I thought would be very simple to fix. I have a service method similar to this:
#Transactional
public void deleteObject(ObjectClass object)
{
this.objectClassDAO.delete(object);
}
I need to display a friendly message when the user tries to delete an object which is related to another entity. The problem I have is that the ConstraintViolationException is thrown until commit() is called, which runs outside of the scope of my service method. Is there a way to let spring call some intermediate code in the event of a particular exception, so that I can set the proper error message?
I've been searching on google for over an hour with no luck. The approaches I've found that seem at least mildly related seem like overkill and like they run at application level. Is there a simple way to intercept an exception after a commit at method-level?
You're probably using FlushMode.AUTO and the exception is being thrown when the transaction ends (in the proxy around your service created by Spring). You can explicitly call Session.flush() inside of the objectClassDAO.delete() method. You typically don't want to do this, but in this case it will force a synchronization with the underlying persistence and if there is a constraint violation the exception will be thrown before objectClassDAO.delete returns. This may be a last resort though.
We have a Spring based application with a service layer which is annotated with #Transactional. We need to have code run before and after some transactional methods for the following reasons:
We need to synchronize access to the method based on a key. The thread needs to block before the start of the transaction.
We need to post a message on a queue if the transaction succeeds.
The options seem to be:
Create a class with similar methods to the service that can run the #Transactional method in a synchronized block and check for the return then post the message (would need a separate class due to AOP proxy problem). Services calling services, not nice, feels like a work-around.
Write an aspect to wrap around the #Transactional AOP which can do the synchronization and message posting. Might work but would rather avoid AOP.
Move the transaction down to the domain layer. Not desirable or possibly even feasible with the current implementation due to the way domain methods are reused in different workflows.
Code the transaction by hand in the service method and scrap #Transactional.
I would imagine this is a fairly common requirement. Probably I am missing an option 5, which is the obvious one!
I think I'd go with 2 unless you have some specific reasons to avoid AOP. Your problem is a classic example of where AOP can be used and it looks pretty good in the result. Here is a nice example of how to implement that (if you didn't read that already): Advising transactional operations
If AOP is really not an option, I'd go the 'Otherwise' option proposed by #Lawrence McAlpin.
Check out TransactionSynchronization callback interface. Spring can natively inform you what is happening with your transaction.
I would use a TransactionTemplate (your option 4) and programatically control the scope of the transaction in situations like this.
Otherwise, you could move the logic in your method out into a separate service, make that new service #Transactional, remove the #Transactional from the current method, and then surround the call to the new service with your pre- and post-transaction logic. I've taken this approach as well, but I prefer programmatic transaction management for requirements like this, as I think it's cleaner and, as you mentioned, services calling services (that are only ever needed by the first service) just feels like a hackish workaround.
if the key is being passed as part of the method call, then you can use java ReentrantLock to do the job.. its much simpler & cleaner.
As described here, I want to update the user's database by means of catching the exception that occurs when the entity classes don't match. I understand that I could add a catch statement to every db-interface method, but that's error-prone*. Other 'polling methods' are also possible, but they are not interrupt-driven as I want through catching exceptions.
I think what I'm looking for is to catch the exception before it's delivered to the user (possibly to crash the application). I would put there my catch block. I'd have put it in the main() in a non NB app.
My understanding is that the exception is thrown on an entity basis (i.e. a method that involves only one entity, which has not changed, will not throw any exceptions, although other entities have changed).
I had a similar problem, but I guess mine is a bit harder to solve. I use JPA at server side, and the server is actually a webservice provider.
The persistence is managed by the container, and according to my app settings, it uses a "Create" strategy. Of course, every time I change my entities and redeploy the application it throws a lot of exceptions.
What I finally decided to do is to create/migrate the existing database in a separate process. This is, reading the metadata associated to the entities and comparing it with the current database.
Afterwards, it creates a migration script in case the db schema is different to fit it into the new one without losing any information (the migration script generation complexity depends on how do you plan to handle cases like data type changes or attribute removal). The last step is redeploying the app (in your case start it).
I'd suggest a proactive approach, where you don't wait for the exception to be thrown, but trying to guess the changes before to run the application.
imagine a transactional, multithreaded java application using spring, jdbc and aop with n classes in m packages all taking part in database transations. Now let's say there is the need to scope an arbitrary set of classes within one transaction. Furthermore there is always one class T within the scope that commits the transaction when called.
Let me give an example for clarity:
Given the packages A,B,Z and classes A.Foo, B.Bar and Z.T.
The following instances of the respective classes are called (possibly by different callers with other classes in between): A.Foo,B.Bar,A.Foo,Z.T
The transactions will be committed only after Z.T is called. Should the application shut down for whatever reason the transaction will never be committed unless Z.T gets involved.
Instances can call each other and, as already mentioned, there is no common entry point calling all instances from a single point of entry (like a service layer) which would make an easy target for spring's transactional tag.
Now the question: can this problem be solved using aspects ? If so, what could be the basic approach ?
Thanks.
You don't need a single point of entry, but you do need the ability to apply the transactional interceptor to all entry points so that re-entrant calls can participate in the same transaction. Assuming that you can do that, you could accomplish this with a ThreadLocal flag and a custom org.springframework.transaction.support.TransactionSynchronization implementation.
You'd modify Z.T to set the ThreadLocal flag when a commit is safe to proceed. In your TransactionSynchronization.beforeCommit() implementation, which is invoked from the PlatformTransactionManager, you can check the flag and use that to determine whether to allow the commit to proceed. You can force a rollback by throwing a RuntimeException if the flag is not present.
One caveat would be if you have other types of transactions (that don't involve the 3 co-ordinating classes you've described), you'll need to ensure that they don't get rolled back inadvertently. To do this, you could flag this "special transaction" in A.Foo, B.Bar and Z.T via another ThreadLocal flag, then check that flag in a guard clause in the beforeCommit() method mentioned above. Pseudocode:
void beforeCommit() {
if in special transaction
if commit flag not set
throw new RuntimeException("cancel transaction")
end if
end if
end
And, obviously, this is a hack and I wouldn't advocate doing in a greenfield system :).
Spring's idiom would recommend having a service interface that knows about units of work and a persistence interface that deals with relational databases. The methods in the service interface should map closely to your use cases. The service implementation knows about all the model and persistence packages and classes it needs to accomplish the goals of the use case.
"Instances can call each other and, as already mentioned, there is no common entry point calling all instances from a single point of entry (like a service layer) which would make an easy target for spring's transactional tag."
This sentence tells me that you're doing things in a manner that doesn't lend itself so easily to Spring's idiom. It's hard to tell exactly what you want, but it sounds like you're tossing aside two of the most important layers that Spring recommends. If it seems difficult to go against the grain, perhaps it's your design that needs reworking.
"...different callers with other classes in between..." - maybe you need to declare transactions individually on these callers.
You can declare transactions in XML config using aspects, either with Spring AOP or AspectJ. Spring 2.5 and higher now give you the option of using annotations if you prefer them to XML configuration.
Your description is terribly confusing to me. Maybe that's part of the reason you're having difficulty with it as well. I'd rethink or clarify.
With spring transactions and aop you can do it but it'll be a bit of "hack"...
You'll need to put the start of the transaction at all the entry points - you can only commit from when you started the transaction, and you'll need a second aspect inside this one to control whether to commit or not.
Now the only way to tell spring to roll back a transaction is to throw an exception across the transaction boundary. Thus what you'll need to do if you enter that area Z which will cause the commit you'll then need to put something in the thread local (also possibly via an aspect) which that "inner" aspect will find and thus not throw the exception to roll back the transaction. If you do not enter Z then the thread local will not get the flag and when you go back across the inner aspect an exception will get thrown to roll back the transaction. You'll probably have to swallow that exception.