使用
1.JDBCTemplate基本使用
1.编写实体类Account,在bean.xml中配置,DriverManagerDataSource是Spring自带的数据源,不用导包
(实际应用还可参照下面更方便高级)
<!-- 配置账户的持久层-->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></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/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
获取和常用的使用方法。
注意new BeanPropertyRowMapper(Account.class),是spring自带的,让我们更方便的的获取数据并返回。
JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
*查询,返回List<>
*/
public List<User> findAll() {
List<User> users=jdbcTemplate.query("select * from user where id > ?", new BeanPropertyRowMapper<User>(User.class),0);
return users;
}
/**
* queryForObject
*/
public int count() {
return jdbcTemplate.queryForObject("select count(*) from user where id > ?",Integer.class,1);
}
/**
* 更新,增删改
*/
public void update(User user) {
jdbcTemplate.update("update user set name= ? , password= ? where id = ?",user.getName(),user.getPassword(),user.getId());
}
2.JdbcDaoSupport
如果有多个Dao继承要配Jdbc 那么就有很多重复的代码,将Jdbc部分提取出来。
这是Spring封装好的父类,Dao直接继承应用。
XML配置同上
注意 AccountDaoImpl继承JdbcDaoSupport后,就不能用注解的方式来配置AccountDaoImpl到IOC了,那就用XML配置方式配置了。
用super.getJdbcTemplate() 来获取JdbcTemplate对象
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
public Account findAccountById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String accountName) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}