(Spring)注釈に基づくアカウントのCRUD操作例
文書ディレクトリ一、bean.xml 二、AccountDaoImpl.java 三、AccountServiceImpl.java 四、試験類 一、bean.xml
二、AccountDaoImpl.java
三、AccountServiceImpl.java
四、テストクラス
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Spring , , beans
context -->
<context:component-scan base-package="mybatis"></context:component-scan>
<!-- QueryRunner-->
<!-- , -->
<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/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
二、AccountDaoImpl.java
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner runner;
@Override
public List<Account> findAllAccount() {
try {
String sql = "select * from account";
return runner.query(sql,new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
三、AccountServiceImpl.java
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
}
四、テストクラス
public class AccountServiceTest {
@Test
public void testFindAll(){
//1. spring
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.
AccountService as = (AccountService) ac.getBean("accountService");
//3.
List<Account> accounts = as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
}