什么是JdbcTemplate:Spring框架对JDBC进行封装,使用JdbcTemplate方便实现对数据库操作
具体步骤:
1、导入相关jar包:
2、编写bean1.xml,开启组件扫描、配置数据库连接池、配置JdbcTemplate对象,注入DataSource
<?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" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 开启组件扫描--> <context:component-scan base-package="demo"></context:component-scan> <!-- 数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="jdbc:mysql:///user_db" /> <property name="username" value="root" /> <property name="password" value="root" /> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> </bean> <!-- jdbcTemplate对象 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!-- 注入dataSource --> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
3、创建BookDao接口
1. package demo.dao; 2. 3. public interface BookDao { 4. }
4、创建BookDaoImpl类,继承BookDao接口,并注入JdbcTemplate对象
package demo.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 { //注入jdbcTemplate @Autowired private JdbcTemplate jdbcTemplate; }
5、创建BookService类,并注入dao
package demo.service; import demo.dao.BookDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookService { //注入dao @Autowired private BookDao bookDao; }