导入的jar包:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
文件结构:
Dao层实现类:
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jt;
public void setJt(JdbcTemplate jt) {
this.jt = jt;
}
@Override
public Account findById(int id) {
List<Account> list = jt.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findByName(String name) {
List<Account> list = jt.query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), name);
if(list.isEmpty()){
return null;
}
if(list.size()>0){
throw new RuntimeException("结果不唯一,查询条件有误");
}
return list.get(0);
}
@Override
public void saveAccount(Account account) {
jt.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
配置文件:
<?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">
<!-- 配置Dao层对象-->
<bean id="accountDao" class="com.itheima.dao.Impl.AccountDaoImpl">
<property name="jt" ref="jdbcTemplate"></property>
<!-- <property name="dataSource" ref="dataSource"></property>-->
</bean>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/1906?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>