Spring中的JdbcTemplate
Posted 心默默言
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring中的JdbcTemplate相关的知识,希望对你有一定的参考价值。
1.JdbcTemplate概述
2.JdbcTemplate最基本的使用
2.1导入jar包
<?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>com.itheima</groupId> <artifactId>day04_eesy_01jdbctemplate</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>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> </project>
2.2实体类
package com.itheima.domain; import java.io.Serializable; /** * 账户的实体类 */ public class Account implements Serializable { private Integer id; private String name; private Float money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getMoney() { return money; } public void setMoney(Float money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name=\'" + name + \'\\\'\' + ", money=" + money + \'}\'; } }
2.3测试
package com.itheima.jdbctemplate; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * JdbcTemplate的最基本用法 */ public class JdbcTemplateDemo1 { public static void main(String[] args) { //准备数据源:spring的内置数据源 DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/eesy"); ds.setUsername("root"); ds.setPassword("123456"); //1.创建JdbcTemplate对象 JdbcTemplate jt = new JdbcTemplate(); //给jt设置数据源 jt.setDataSource(ds); //2.执行操作 jt.execute("insert into account(name,money)values(\'ccc\',1000)"); } }
3.JdbcTemplate在spring的ioc中使用
3.1配置文件bean.xml
<?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"> <!--配置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="123456"></property> </bean> </beans>
3.2测试
package com.itheima.jdbctemplate; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * JdbcTemplate的最基本用法 */ public class JdbcTemplateDemo2 { public static void main(String[] args) { //1.获取容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.获取对象 JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class); //3.执行操作 jt.execute("insert into account(name,money)values(\'ddd\',2222)"); } }
4.JdbcTemplate的CRUD操作
package com.itheima.jdbctemplate; import com.itheima.domain.Account; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * JdbcTemplate的CRUD操作 */ public class JdbcTemplateDemo3 { public static void main(String[] args) { //1.获取容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.获取对象 JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class); //3.执行操作 //保存 // jt.update("insert into account(name,money)values(?,?)", "eee", 3333f); //更新 // jt.update("update account set name=?,money=? where id=?", "test", 4567, 7); //删除 // jt.update("delete from account where id=?", 8); //查询所有 // List<Account> accounts = jt.query("select * from account where money > ?",new AccountRowMapper() , 1000f); //spring提供的封装结果集,不用自己写封装类AccountRowMapper,直接用spring提供的就可以了 // List<Account> accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),1000f); // for (Account account : accounts) { // System.out.println(account); // } //查询一个 // List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1); // System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0)); //查询返回一行一列(使用聚合函数,但不加group by子句) Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f); System.out.println(count); } } class AccountRowMapper implements RowMapper<Account> { /** * 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中 * * @param rs * @param rowNum * @return * @throws SQLException */ @Override public Account mapRow(ResultSet rs, int rowNum) throws SQLException { Account account = new Account(); account.setId(rs.getInt("id")); account.setName(rs.getString("name")); account.setMoney(rs.getFloat("money")); return account; } }
5.JdbcTemplate在Dao中的使用
5.1接口
package com.itheima.dao; import com.itheima.domain.Account; /** * 账户的持久层接口 */ public interface IAccountDao { /** * 根据Id查询账户 * @param accountId * @return */ Account findAccountById(Integer accountId); /** * 根据名称查询账户 * @param accountName * @return */ Account findAccountByName(String accountName); /** * 更新账户 * @param account */ void updateAccount(Account account); }
5.2接口的实现类
package com.itheima.dao.impl; import com.itheima.dao.IAccountDao; import com.itheima.domain.Account; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; /** * 账户的持久层实现类 */ public class AccountDaoImpl implements IAccountDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public Account findAccountById(Integer accountId) { List<Account> accounts = jdbcTemplate.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 = jdbcTemplate.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) { jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId()); } }
5.3配置文件
<?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"> <!-- 配置账户的持久层--> <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="123456"></property> </bean> </beans>
5.4测试类
package com.itheima.jdbctemplate; import com.itheima.dao.IAccountDao; import com.itheima.domain.Account; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; /** * JdbcTemplate的最基本用法 */ public class JdbcTemplateDemo4 { public static void main(String[] args) { //1.获取容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.获取对象 IAccountDao accountDao = ac.getBean("accountDao",IAccountDao.class); Account account = accountDao.findAccountById(1); System.out.println(account); account.setMoney(10000f); accountDao.updateAccount(account); } }
以上是关于Spring中的JdbcTemplate的主要内容,如果未能解决你的问题,请参考以下文章