/**
 * 
 */
package jp.terasoluna.batch.functionsample.b001;

import jp.terasoluna.fw.batch.exception.BatchException;
import jp.terasoluna.fw.batch.util.BatchUtil;
import jp.terasoluna.fw.dao.UpdateDAO;
import jp.terasoluna.fw.dao.event.DataRowHandler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;

/**
 * DB関連ジョブのサンプル<br>
 * <br>
 * RowHandler内で複数データソースを利用し1件ずつコミットするサンプル。<br>
 * 85件以上は実行例外をスローし、ロールバックする。
 */
public class B001009DataRowHandler implements DataRowHandler {

	private Log log = LogFactory.getLog(B001009DataRowHandler.class);

	@Autowired
	@Qualifier("updateDAO1")
	private UpdateDAO updateDAO = null;

	@Autowired
	@Qualifier("transactionManager1")
	private PlatformTransactionManager transactionManager = null;

	public void handleRow(Object arg) {

		TransactionStatus stat = null;
		B001009Param param = null;

		if (arg instanceof B001009Param) {
			param = (B001009Param) arg;
		}

		stat = BatchUtil.startTransaction(transactionManager);

		try {

			param.setFamilyName("鈴木");
			param.setFirstName("次郎");

			if (param.getId() >= 85) {
				log.error("85件以上は実行例外をスローする");
				throw new BatchException();
			}

			updateDAO.execute("B001009.updateEmployee", param);
			BatchUtil.commitTransaction(transactionManager, stat);

		} catch (BatchException e) {
			BatchUtil.rollbackTransaction(transactionManager, stat);
			log.error(e);
		} finally {
			BatchUtil.endTransaction(transactionManager, stat);
		}
	}
}
