言成言成啊 | Kit Chen's Blog

JdbcTemplate以及事务控制

一、JdbcTemplate

1.1 概述

JdbcTemplate是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装。

Spring框架提供的工具类

  1. 关系型数据库
    • JdbcTemplate
    • HibernateTemplate
  2. 非关系型数据库
    • RedisTemplate
  3. 操作消息队列
    • JmsTemplate

JdbcTemplate的作用:它就是与数据库交互的,实现对表的CRUD操作

1.2 使用

简单使用

可以直接用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class JdbcTemplateDemo01 {
public static void main(String[] args) {
//准备数据源:Spring的内置数据源
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/spring?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
ds.setUsername("root");
ds.setPassword("root");
//1.创建JdbcTemplate对象
JdbcTemplate jt=new JdbcTemplate();
jt.setDataSource(ds);
//2. 执行操作
jt.execute("insert into account(name,money)values('ccc',1000)");
}
}

Spring注解使用

Config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
@ComponentScan("top.meethigher.demo19")
@EnableAspectJAutoProxy
public class Config {
@Bean("ds")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/spring?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
@Bean("jdbcTemplate")
public JdbcTemplate createJdbcTemplate(@Qualifier("ds") DataSource ds){
return new JdbcTemplate(ds);
}
}

Account

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;

@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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;
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class JdbcTemplateDemo02 {
public static void main(String[] args) {
AnnotationConfigApplicationContext aac = new AnnotationConfigApplicationContext(Config.class);
// JdbcTemplate jdbcTemplate = (JdbcTemplate) aac.getBean("jdbcTemplate");
JdbcTemplate jdbcTemplate = aac.getBean("jdbcTemplate", JdbcTemplate.class);
//插入
// jdbcTemplate.execute("insert into account(name,money)values('ddd',2222)");
//修改
// jdbcTemplate.update("update account set name=?,money=? where id=?","bbb",111,13);
//删除
// jdbcTemplate.update("delete from account where id=?",13);
//查询所有
// List<Account> query = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<>(Account.class));
// System.out.println(query);
//查询一个
// List<Account> query = jdbcTemplate.query("select * from account where id=?", new BeanPropertyRowMapper<>(Account.class), 1);
// System.out.println(query.get(0));
//查询总记录数
Long aLong = jdbcTemplate.queryForObject("select count(*) from account where money>?", Long.class, 1000);
System.out.println(aLong);
}
}

Spring与Dao的联合使用的两种方式

使用注解的dao层来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Component("accoundDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account findAccountById(Integer accountId) {
List<Account> query = jdbcTemplate.query("select * from account where id=?", new BeanPropertyRowMapper<>(Account.class), accountId);
if(query.isEmpty()){
return null;
}
return query.get(0);
}

@Override
public Account findAccountByName(String name) {
List<Account> query = jdbcTemplate.query("select * from account where name=?", new BeanPropertyRowMapper<>(Account.class), name);
if(query.isEmpty()){
return null;
}
if(query.size()>1){
throw new RuntimeException("结果不唯一");
}
return query.get(0);
}

@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}

使用xml的dao层来实现

但是如果有很多个dao的话,就会有重复代码了,那么如何解决?

我们可以通过创建一个dao的共有父类,让其他子类继承

而spring中,提供了这种个父类JdbcDaoSupport

AccountDaoImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer accountId) {
List<Account> query = super.getJdbcTemplate().query("select * from account where id=?", new BeanPropertyRowMapper<>(Account.class), accountId);
if(query.isEmpty()){
return null;
}
return query.get(0);
}

@Override
public Account findAccountByName(String name) {
List<Account> query = super.getJdbcTemplate().query("select * from account where name=?", new BeanPropertyRowMapper<>(Account.class), name);
if(query.isEmpty()){
return null;
}
if(query.size()>1){
throw new RuntimeException("结果不唯一");
}
return query.get(0);
}

@Override
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="accountDao" class="top.meethigher.demo20.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="ds"/>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>

测试类

1
2
3
4
5
6
7
8
9
public class JdbcTemplateDemo03 {
public static void main(String[] args) {
ClassPathXmlApplicationContext aac = new ClassPathXmlApplicationContext("spring.xml");
AccountDaoImpl accoundDao = aac.getBean("accountDao", AccountDaoImpl.class);
System.out.println(accoundDao.findAccountById(1));
// System.out.println(accoundDao.findAccountByName("水冰儿"));
System.out.println(accoundDao.findAccountByName("小舞"));
}
}

二、事务控制

发布:2021-04-05 03:04:24
修改:2021-04-05 23:52:17
链接:https://meethigher.top/blog/2021/spring3/
标签:spring 
付款码 打赏 分享
阅读量