基於xml和註解的SpringIoC實現單表CRUD

數據庫表

在這裏插入圖片描述

xml實現

domain(省略get/set和toString方法)

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;
}

持久層接口及實現類

public interface IAccountDao {
    /**
     * 查詢所有
     *
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查詢一個
     *
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 保存賬戶
     *
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新賬戶
     *
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 刪除賬戶
     *
     * @param id
     */
    void deleteAccount(Integer id);
}

public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        String sql = "select * from account";
        try {
            return runner.query(sql, new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer id) {
        String sql = "select * from account where id = ?";
        try {
            return runner.query(sql, new BeanHandler<Account>(Account.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        String sql = "insert into account(name,money)values(?,?)";
        try {
            runner.update(sql, account.getName(), account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        String sql = "update account set name = ?,money = ? where id = ?";
        try {
            runner.update(sql, account.getName(), account.getMoney(), account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer id) {
        String sql = "delete from account where id = ?";
        try {
            runner.update(sql, id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

業務層接口及實現類

public interface IAccountService {
    /**
     * 查詢所有
     *
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查詢一個
     *
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 保存賬戶
     *
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新賬戶
     *
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 刪除賬戶
     *
     * @param id
     */
    void deleteAccount(Integer id);
}

public class IAccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
}

配置文件

   <bean id="accountService" class="com.sx.service.impl.IAccountServiceImpl">
      <property name="accountDao" ref="accountDao"></property>
   </bean>

   <bean id="accountDao" class="com.sx.dao.impl.AccountDaoImpl">
      <property name="runner" ref="runner"></property>
   </bean>

   <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
      <constructor-arg name="ds" ref="dataSource">

      </constructor-arg>

   </bean>

   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
      <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
      <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy_spring"></property>
      <property name="user" value="root"></property>
      <property name="password" value="123456"></property>
   </bean>

註解實現

持久層實現類

方法同上
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;
}

服務層實現類

方法同上
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;
}

創建配置類

@Configuration
@ComponentScan(basePackages = {"com.sx"})
@Import(JdbcConfig.class)
public class SpringConfiguration {

}


@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds1") DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    @Bean(name = "ds1")
    public DataSource createDataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }

    }
}

Spring和Junit整合

Spring整合junit的配置
	1.導入Spring整合junit的座標
	2.使用Junit提供的一個註解把原有的main方法替換,替換成Spring提供的
		@Runwith
	3.告知Spring的運行器,Spring和IoC創建是基於xml還是註解的,並且說明位置
		@ContextConfiguration
			locations屬性:指定xml文件的位置,加上classpath關鍵字,表示在類路徑下
			classes屬性:指定註解類所在地位置
 *   當使用spring 5.x版本的時候,要求junit的jar必須是4.12及以上
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    @Autowired
    private IAccountService accountService;

    @Test
    public void testFindAll() {
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("ddd");
        account.setMoney(1000f);
        accountService.saveAccount(account);
    }

    @Test
    public void testUpdate() {
        Account account = new Account();
        account.setId(4);
        account.setName("eee");
        account.setMoney(2000f);
        accountService.updateAccount(account);
    }

    @Test
    public void testDelete() {
        accountService.deleteAccount(4);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章