Transactions With Spring in Java

No Gravatar

This post will show you how to write the code to perform transaction handling in Java using the Spring framework. There are certainly many varied ways to handle this, but this is one that I’ve found works fairly well and tends to lead to a fairly clean code base.
The code below essentially forces the block of code all to occur within a transaction, and either causes the transaction to go through with a commit (assuming everything went well), or rolls it all back if anything failed. In this particular case, there are multiple stored procedures being called that all need to pass for the entire process to be valid. It’s true that this could all be handled in one procedure, but that could make the parameters very ugly. In this situation, I think it’s better to have multiple procedures called within one transaction in the java code.

public boolean saveUser(User user){
	boolean success = false;

	DefaultTransactionDefinition def = new DefaultTransactionDefinition();

	TransactionStatus status = transactionManager.getTransaction(def);
	Map results = null;

		LinkedHashMap inputTypesMap = new LinkedHashMap();
		inputTypesMap.put(Constants.USER_ID,new Integer(Types.INTEGER));
		inputTypesMap.put(Constants.FIRST_NAME,new Integer(Types.VARCHAR));
		inputTypesMap.put(Constants.LAST_NAME,new Integer(Types.VARCHAR));
		inputTypesMap.put(Constants.PHONE_NUMBER,new Integer(Types.VARCHAR));
		inputTypesMap.put(Constants.EMAIL_ADDRESS,new Integer(Types.VARCHAR));
		LinkedHashMap outputTypesMap = new LinkedHashMap();
		AdminStoredProcedure prc =
			new AdminStoredProcedure(ds,Constants.USER_SAV_PROCEDURE_NAME,
		LinkedHashMap inputValuesMap = new LinkedHashMap();
                inputValuesMap.put(Constants.USER_ID, user.getUserId());

		results = prc.execute(inputValuesMap);

		//another procedure call, hence the need for the transaction
		int[] contactGroups = user.getContactGroups();
		for(int i=0; i

Hope this helps.

Be Sociable, Share!