-
什么是JdbcTemplate
- Spring对JDBC进行了封装——JDBC模板,通过它实现对数据库的增删改操作。
-
准备工作
- 引入jar包:(1)mysql依赖:在哪下载Mysql数据库的JDBC驱动jar包__清风明月的博客-CSDN博客_mysql驱动jar包在哪(2)德鲁伊druid连接池:Central Repository: com/alibaba/druid(3)spring jdbc(4)spring tx(事务)(5)spring orm(整合Mybatis操作数据库需要)
- 在Spring配置文件中配置数据库的连接池。
<!--数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///myemployees"/>
<property name="username" value="root"/>
<property name="password" value="950728"/>
</bean>
?????????????????3.配置JdbcTemplate对象,注入Datasource?
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--JdbcTemplate对象中注入DataSource,源码中是使用setDataSource()方法-->
<property name="dataSource" ref="dataSource"></property>
</bean>
? ? ? ? ? ? ? ? 4.创建一个Service类和Dao类,在Service里面注入Dao,在Dao中注入Jdbc Template对象
在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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.company"></context:component-scan>
在Service里面注入dao
package com.company.service;
import com.company.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookService {
//在Service里面注入dao
@Autowired
private BookDao bookDao;
}
?在dao里面注入jdbc template
package com.company.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookDaoImpl implements BookDao {
//dao里面注入JdbcTemplate
@Autowired
private JdbcTemplate jdbctemplate;
}
3.JdbcTemplate操作数据库
- ?对应数据库表先创建出实体类User类
package com.company.entity;
public class User {
private String userId;
private String userName;
private String userEmail;
//get set方法
public String getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
}
?
|