View Javadoc

1   /*
2    * Copyright 2006-2007 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.batch.sample.domain.trade.internal;
18  
19  import java.math.BigDecimal;
20  import java.sql.ResultSet;
21  import java.sql.SQLException;
22  import java.util.List;
23  
24  import org.springframework.batch.sample.domain.trade.CustomerCredit;
25  import org.springframework.batch.sample.domain.trade.CustomerDao;
26  import org.springframework.jdbc.core.RowMapper;
27  import org.springframework.jdbc.core.support.JdbcDaoSupport;
28  import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
29  
30  /**
31   * @author Lucas Ward
32   *
33   */
34  public class JdbcCustomerDao extends JdbcDaoSupport implements CustomerDao{
35  
36  	private static final String GET_CUSTOMER_BY_NAME = "SELECT ID, NAME, CREDIT from CUSTOMER where NAME = ?";
37  	private static final String INSERT_CUSTOMER = "INSERT into CUSTOMER(ID, NAME, CREDIT) values(?,?,?)";
38  	private static final String UPDATE_CUSTOMER = "UPDATE CUSTOMER set CREDIT = ? where NAME = ?";
39  	
40  	private DataFieldMaxValueIncrementer incrementer;
41  	
42  	public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
43  		this.incrementer = incrementer;
44  	}
45  	
46  	public CustomerCredit getCustomerByName(String name) {
47  		
48  		@SuppressWarnings("unchecked")
49  		List<CustomerCredit> customers = (List<CustomerCredit>) getJdbcTemplate().query(GET_CUSTOMER_BY_NAME, new Object[]{name}, 
50  				
51  				new RowMapper(){
52  
53  			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
54  				CustomerCredit customer = new CustomerCredit();
55  				customer.setName(rs.getString("NAME"));
56  				customer.setId(rs.getInt("ID"));
57  				customer.setCredit(rs.getBigDecimal("CREDIT"));
58  				return customer;
59  			}
60  			
61  		});
62  	
63  		if(customers.size() == 0){
64  			return null;
65  		}
66  		else{
67  			return customers.get(0);
68  		}
69  		
70  	}
71  
72  	public void insertCustomer(String name, BigDecimal credit) {
73  		
74  		getJdbcTemplate().update(INSERT_CUSTOMER, new Object[]{incrementer.nextIntValue(), name, credit});
75  	}
76  
77  	public void updateCustomer(String name, BigDecimal credit) {
78  		getJdbcTemplate().update(UPDATE_CUSTOMER, new Object[]{credit, name});
79  	}
80  
81  }