此内容没有您所选择的语言版本。
Appendix B. AccountService Example
Abstract
The
AccountService
example class illustrates how you can use Spring JdbcTemplate
class to access a JDBC data source.
B.1. AccountService Example Code
Overview
The
AccountService
class provides a simple example of accessing a data source through JDBC. The methods in this class can be used inside a local transaction or inside a global (XA) transaction.
Database schema
The
AccountService
example requires a single database table, accounts
, which has two columns: a name
column (containing the account name), and an amount
column (containing the dollar balance of the account). The required database schema can be created by the following SQL statement:
CREATE TABLE accounts (name VARCHAR(50), amount INT);
AccountService class
Example B.1, “The AccountService Class” shows the complete listing of the
AccountService
class, which uses the Spring JdbcTemplate
class to access a JDBC data source.
Example B.1. The AccountService Class
// Java package org.fusesource.example.tx.xa; import java.util.List; import javax.sql.DataSource; import org.apache.camel.Exchange; import org.apache.camel.language.XPath; import org.apache.log4j.Logger; import org.springframework.jdbc.core.JdbcTemplate; public class AccountService { private static Logger log = Logger.getLogger(AccountService.class); private JdbcTemplate jdbc; public AccountService() { } public void setDataSource(DataSource ds) { jdbc = new JdbcTemplate(ds); } public void credit( @XPath("/transaction/transfer/receiver/text()") String name, @XPath("/transaction/transfer/amount/text()") String amount ) { log.info("credit() called with args name = " + name + " and amount = " + amount); int origAmount = jdbc.queryForInt( "select amount from accounts where name = ?", new Object[]{name} ); int newAmount = origAmount + Integer.parseInt(amount); jdbc.update( "update accounts set amount = ? where name = ?", new Object[] {newAmount, name} ); } public void debit( @XPath("/transaction/transfer/sender/text()") String name, @XPath("/transaction/transfer/amount/text()") String amount ) { log.info("debit() called with args name = " + name + " and amount = " + amount); int iamount = Integer.parseInt(amount); if (iamount > 100) { throw new IllegalArgumentException("Debit limit is 100"); } int origAmount = jdbc.queryForInt( "select amount from accounts where name = ?", new Object[]{name} ); int newAmount = origAmount - Integer.parseInt(amount); if (newAmount < 0) { throw new IllegalArgumentException("Not enough in account"); } jdbc.update( "update accounts set amount = ? where name = ?", new Object[] {newAmount, name} ); } public void dumpTable(Exchange ex) { log.info("dump() called"); List<?> dump = jdbc.queryForList("select * from accounts"); ex.getIn().setBody(dump.toString()); } }