JdbcTemplate的用法

JdbcTemplate的用法

0. 导入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

1. 最基本的用法

实际也不会这样用吧应该

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
// 准备数据源:spring的内置数据源
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/jdbcdb?useUnicode=true&characterEncoding=utf8");
ds.setUsername("root");
ds.setPassword("root");

// 1.创建JdbcTemplate对象
JdbcTemplate jt = new JdbcTemplate();
//给jt设置数据源
jt.setDataSource(ds);
// 2.执行操作
jt.execute("insert into account(name, money)values ('ccc',1000)");
}
}

2. 在xml中配置

1
2
3
4
5
6
7
8
9
10
11
12
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<!--配置dataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/jdbcdb?useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
1
2
3
4
5
6
7
8
9
10
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
// 1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.获取对象
JdbcTemplate template = ac.getBean("jbcTemplate",JdbcTemplate.class);
// 3.执行操作
template.execute("insert into account(name, money)values ('ddd',1000)");
}
}

3. 在持久层中调用

3.1 继承JdbcDaoSupport

不用在配置文件中修改

1
2
3
4
5
6
7
8
9
10
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

private JdbcTemplate jdbcTemplate;

public AccountDaoImpl() {
this.jdbcTemplate = super.getJdbcTemplate();
}

//然后就可以用 jdbcTemplate 的query update等方法了
}

3.2 使用注解配置

  1. 在spring的配置文件中配置好了 jdbcTemplate 并配置好数据源
  2. 在持久层中用 @Autowired 注入 jdbcTemplate
  • Copyrights © 2020-2023 夕子学姐
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信