Class TransactionFactory
The TransactionFactory exposes a number of convenience methods specifically for managing transactions in a persistence store.
This is necessary when making changes to a resource that is persisted, such as the creation of entities.
In some situations the transaction is generated automatically by the Platform (i.e., when servicing a request), in which case the default
transaction can be used. For any code that executes outside of a request or in a separate thread, it is necessary to create your own
transaction.
Transactions can be nested safely. The transaction success status owned by ThreadLocalContext is separate from this nesting logic and should indicate overall success of the process and not the individual
transaction.
The following is an example of using transactions:
try {
String username = "user";
String groupName = "group";
ThreadLocalContext.setSecurityContext(SecurityContext.createSystemUserContext());
TransactionFactory.beginTransactionRequired();
EntityServices entityServices = (EntityServices) EntityUtilities.findEntity("EntityServices", ThingworxRelationshipTypes.Resource);
entityServices.CreateUser(username, null, null, username);
User user = (User) EntityUtilities.findEntity(username, ThingworxRelationshipTypes.User);
Group grp = (Group) EntityUtilities.findEntity(groupName, ThingworxRelationshipTypes.Group);
if (grp != null) {
user.addGroup(grp);
}
} catch (Exception e) {
ThreadLocalContext.setTransactionSuccess(false);
TransactionFactory.failure();
} finally {
TransactionFactory.endTransactionRequired();
ThreadLocalContext.clearSecurityContext();
}
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic voidBegin a transactionstatic voidEnd the transactionstatic voidfailure()Fail the transaction
-
Constructor Details
-
TransactionFactory
public TransactionFactory()Initializes this instace with default values.
-
-
Method Details
-
failure
Fail the transaction -
beginTransactionRequired
@ThingworxExtensionApiMethod(since={6,6}) public static void beginTransactionRequired() throws ExceptionBegin a transaction- Throws:
Exception- If an error occurs
-
endTransactionRequired
End the transaction
-