SpringJdbcTemplate是spring框架中提供的一个对象,是对原始JDBC API对象的简单封装。spring框架为我们提供了很多的操作模板类。
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<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">
beans>
直接通过new的方式获取JdbcTemplate对象,并使用其中的query()
实现查询所有或者根据具体条件查询;使用update()
执行保存、更新、删除操作;使用queryforObject()
使用SQL中的聚合函数执行查询……
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/sql_store?serverTimezone=GMT");
ds.setUsername("root");
ds.setPassword("1234");
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(ds);
// 查询所有
List<Account> accounts = jt.query("select * from account where money = ?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
for(Account account : accounts){
System.out.println(account);
}
// 保存
jt.update("insert into account(name,money)values(?,?)","Ball",1000f);
// 更新
jt.update("update account set name=?,money=? where id=?","Amy", 2000, 1);
// 删除
jt.update("delete from account where id=?",1);
// 查询一个
List<Account> accounts1 = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
System.out.println(accounts.isEmpty()?"没有内容":accounts1.get(0));
//查询返回一行一列(使用聚合函数,但不加group by子句)
Long count = jt.queryForObject("select count(*) from account where money = ?",Long.class,1000f);
System.out.println(count);
}
}
account表中的内容如下:
mysql> select * from account;
+----+----------+-------+
| id | name | money |
+----+----------+-------+
| 1 | Forlogen | 1000 |
| 2 | Kobe | 1000 |
| 3 | James | 1000 |
+----+----------+-------+
3 rows in set (0.00 sec)
创建实体类:
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 +
'}';
}
}
创建持久层接口:
public interface IAccountDao {
Account findAccountById(Integer accountId);
Account findAccountByName(String accountName);
void updateAccount(Account account);
}
创建接口的实现类,并继承JdbcSupport。此时执行查询等操作时调用的方法所需参数是不同的:
public class IAccountDaoImpl1 extends JdbcSupport implements IAccountDao {
@Autowired
private 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());
}
}
JdbcSupport自定义如下:
public class JdbcSupport {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setDataSource(DataSource dataSource) {
if(jdbcTemplate == null){
jdbcTemplate = createJdbcTemplate(dataSource);
}
}
private JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
创建bean.xml文件,在容器中注入JdbcTemplate:
<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="dyliang.dao.impl.IAccountDaoImpl1">
<property name="jdbcTemplate" ref="jdbcTemplate">property>
bean>
<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.cj.jdbc.Driver">property>
<property name="Url" value="jdbc:mysql://localhost:3306/sql_store?serverTimezone=GMT">property>
<property name="username" value="root">property>
<property name="password" value="1234">property>
bean>
beans>
最后获取JdbcTemplate对象,调用query()
实现查询功能:
public class JdbcTempalteDemo2 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
List<Account> accounts = jt.query("select * from account where money = ?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
for(Account account : accounts){
System.out.println(account);
}
}
}
Account{id=1, name='Forlogen', money=1000.0}
Account{id=2, name='Kobe', money=1000.0}
Account{id=3, name='James', money=1000.0}
或者通过accountDao直接调用持久层接口实现类中的方法:
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);
Account accountById = accountDao.findAccountById(1);
System.out.println(accountById);
}
}
Account{id=1, name='Forlogen', money=1000.0}