001/*
002 * Copyright 2006-2012 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.sample.domain.trade.internal;
018
019import javax.sql.DataSource;
020
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.springframework.batch.sample.domain.trade.Trade;
024import org.springframework.batch.sample.domain.trade.TradeDao;
025import org.springframework.jdbc.core.JdbcOperations;
026import org.springframework.jdbc.core.JdbcTemplate;
027import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
028
029
030/**
031 * Writes a Trade object to a database
032 *
033 * @author Robert Kasanicky
034 */
035public class JdbcTradeDao implements TradeDao {
036        private Log log = LogFactory.getLog(JdbcTradeDao.class);
037    /**
038     * template for inserting a row
039     */
040    private static final String INSERT_TRADE_RECORD = "INSERT INTO TRADE (id, version, isin, quantity, price, customer) VALUES (?, 0, ?, ? ,?, ?)";
041
042    /**
043     * handles the processing of SQL query
044     */
045    private JdbcOperations jdbcTemplate;
046
047    /**
048     * database is not expected to be setup for auto increment
049     */
050    private DataFieldMaxValueIncrementer incrementer;
051
052    /**
053     * @see TradeDao
054     */
055    @Override
056        public void writeTrade(Trade trade) {
057        Long id = incrementer.nextLongValue();
058        log.debug("Processing: " + trade);
059        jdbcTemplate.update(INSERT_TRADE_RECORD,
060                                id, trade.getIsin(), trade.getQuantity(), trade.getPrice(),
061                                trade.getCustomer());
062    }
063
064    public void setDataSource(DataSource dataSource) {
065        this.jdbcTemplate = new JdbcTemplate(dataSource);
066    }
067
068    public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
069        this.incrementer = incrementer;
070    }
071
072}