-- 建立數據庫 CREATE DATABASE mydatabase; -- 使用數據庫 USE mydatabase; -- 建立帳戶表 CREATE TABLE account( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40), money FLOAT )CHARACTER SET utf8 COLLATE utf8_general_ci; -- 插入數據 INSERT INTO account(name,money) VALUES('aaa',1000); INSERT INTO account(name,money) VALUES('bbb',1000); INSERT INTO account(name,money) VALUES('ccc',1000);
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>spring_02_crud_xml</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> </project>
public class Account implements Serializable { private Integer id; private String name; private Float money; // setter/getter/構造略 }
public interface AccountDao { /** * 查詢全部 * @return */ List<Account> findAll(); /** * 根據ID查詢帳戶 * @return */ Account findAccountById(Integer id); /** * 保存帳戶 * @param account */ void saveAccount(Account account); /** * 更新帳戶 * @param account */ void updateAccount(Account account); /** * 根據ID刪除指定帳戶 * @param id */ void deleteAccount(Integer id); }
/** * <!-- 註冊AccountDao對象 --> * <bean id="accountDao" class="com.itcast.dao.impl.AccountDaoImpl"> * <!-- 注入QueryRunner對象 --> * <!-- 因爲在本案例中QueryRunner對象爲必須存在的對象,因此使用構造注入防止存在爲空的狀況(構造注入爲強制注入,不容許不注入) --> * <constructor-arg name="queryRunner" ref="queryRunner"></constructor-arg> * </bean> */ @Repository(value = "accountDao") public class AccountDaoImpl implements AccountDao { @Resource(name = "queryRunner") private QueryRunner queryRunner; public AccountDaoImpl(QueryRunner queryRunner) { this.queryRunner = queryRunner; } public List<Account> findAll() { try { return queryRunner.query("SELECT * FROM account", new BeanListHandler<Account>(Account.class)); }catch (Exception e) { throw new RuntimeException(e); } } public Account findAccountById(Integer id) { try { return queryRunner.query("SELECT * FROM account WHERE id = ?", new BeanHandler<Account>(Account.class), id); }catch (Exception e) { throw new RuntimeException(e); } } public void saveAccount(Account account) { try { queryRunner.update("INSERT INTO account(name, money) values(?,?)", account.getName(), account.getMoney()); }catch (Exception e) { throw new RuntimeException(e); } } public void updateAccount(Account account) { try { queryRunner.update("UPDATE account SET name = ?, money = ? WHERE id = ?", account.getName(), account.getMoney(), account.getId()); }catch (Exception e) { throw new RuntimeException(e); } } public void deleteAccount(Integer id) { try { queryRunner.update("DELETE FROM account WHERE id = ?", id); }catch (Exception e) { throw new RuntimeException(e); } } }
public interface AccountService { /** * 查詢全部 * @return */ List<Account> findAll(); /** * 根據ID查詢帳戶 * @param id * @return */ Account findAccountById(Integer id); /** * 保存帳戶 * @param account */ void saveAccount(Account account); /** * 更新帳戶 * @param account */ void updateAccount(Account account); /** * 根據ID刪除指定帳戶 * @param id */ void deleteAccount(Integer id); }
/** * <!-- 註冊AccountService對象 --> * <bean id="accountService" class="com.itcast.service.impl.AccountServiceImpl"> * <!-- 注入AccountDao對象 --> * <property name="accountDao" ref="accountDao"></property> * </bean> */ @Service(value = "accountService") public class AccountServiceImpl implements AccountService { @Resource(name = "accountDao") private AccountDao accountDao; public AccountServiceImpl() { } // 使用註解注入時不須要相對應的setter方法 // public AccountDao getAccountDao() { // return accountDao; // } // // public void setAccountDao(AccountDao accountDao) { // this.accountDao = accountDao; // } public List<Account> findAll() { return this.accountDao.findAll(); } public Account findAccountById(Integer id) { return this.accountDao.findAccountById(id); } public void saveAccount(Account account) { this.accountDao.saveAccount(account); } public void updateAccount(Account account) { this.accountDao.updateAccount(account); } public void deleteAccount(Integer id) { this.accountDao.deleteAccount(id); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 註冊QueryRunner對象 --> <!-- Bean模式是單例模式,queryRunner可能會存在會被多個dao對象同時使用的狀況(即多個線程同時操做同一個對象), 可能會存在問題,因此此處將該對象設置成多例的 --> <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <!-- 注入數據源對象,此處使用c3p0的數據源 --> <constructor-arg name="ds" ref="datasource"></constructor-arg> </bean> <!-- 註冊c3p0數據源對象 --> <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置數據源必備信息:driver、url、username、password --> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydatabase"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> </beans>
public class AccountServiceTest { @Test public void testFindAll() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = ac.getBean("accountService", AccountService.class); List<Account> accounts = accountService.findAll(); for (Account account : accounts) { System.out.println(account); } } @Test public void testFindAccountById() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = ac.getBean("accountService", AccountService.class); Account account = accountService.findAccountById(1); System.out.println(account); } @Test public void testSaveAccount() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = ac.getBean("accountService", AccountService.class); Account account = new Account(); account.setName("ddd"); account.setMoney(1000f); accountService.saveAccount(account); } @Test public void testUpdateAccount() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = ac.getBean("accountService", AccountService.class); Account account = accountService.findAccountById(7); account.setMoney(2000f); accountService.updateAccount(account); } @Test public void testDeleteAccount() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = ac.getBean("accountService", AccountService.class); accountService.deleteAccount(7); } }
testFindAll()的測試結果以下:java
entity{id=1, name='aaa', money=1000.0} entity{id=2, name='bbb', money=1000.0} entity{id=3, name='ccc', money=1000.0}
testFindAccountById()的測試結果以下:mysql
entity{id=1, name='aaa', money=1000.0}
testSaveAccount()的測試結果以下:
spring
testUpdateAccount()的測試結果以下:
sql
testDeleteAccount()的測試結果以下:
數據庫