blob: 9ad846e42fd302f19566dd70288b7f964dbcde26 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
package com.example.spring.bank.account;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
@Repository
public class JDBCAccountRepository implements AccountRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account createAccount() {
final String INSERT_SQL = "insert into account (balance) values(0)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"account_number"});
// ps.setString(1, name);
return ps;
}
}, keyHolder);
Account account = new Account();
// keyHolder.getKey() now contains the generated key
account.setAccountNumber(keyHolder.getKey().intValue());
account.setBalance(new BigDecimal("0.0"));
return account;
}
@Override
public void delete(int accountNumber) {
jdbcTemplate.update("delete from account where account_number = ?", Integer.valueOf(accountNumber));
}
@Override
public List<Account> findAccountsWithLowBalance(BigDecimal lessThanAmount) {
return this.jdbcTemplate.query( "select * from account where balance < ?", new Object[] {lessThanAmount.doubleValue()}, new AccountMapper());
}
@Override
public List<Account> findAllAccounts() {
return this.jdbcTemplate.query( "select * from account", new AccountMapper());
}
@Override
public Account getAccount(int accountNumber) {
return this.jdbcTemplate.queryForObject( "select * from account where account_number = ?", new Object[] {accountNumber}, new AccountMapper());
}
@Override
public void update(Account account) {
this.jdbcTemplate.update("update account set balance = ? where account_number = ?", account.getBalance(), account.getAccountNumber());
}
private static final class AccountMapper implements RowMapper<Account> {
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setAccountNumber(rs.getInt("account_number"));
account.setBalance(rs.getBigDecimal("balance"));
return account;
}
}
}
|