Spring JDBC Template
Spring JDBC Template
JDBCTemplate概述
它是spring框架中提供的一个对象,是对原始繁琐的jdbc API对象的简单封装。Spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的jdbcTemplate和hibernateTemplate,操作nosql数据库的RedisTemplate,操作消息列的JmsTemplate等等。
JDBCTemplate开发步骤
-
导入spring-jdbc和spring-tx坐标
-
创建数据库表和实体
-
创建jdbcTemplate对象
-
执行数据库操作
@Test public void test1()throws Exception{ //创建数据源对象 ComnoPooledDataSource dataSource = new ComboPooledDataSource() dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUser("root"); dataSource.setPassword("1121") JdbcTemplate jdbcTemplate = new JdbcTemplate(); //设置数据源对象,知道数据库在哪 jdbcTemplate.setDataSource(dataSource); //执行操作 int row = jdbcTemplate.update("insert into acccount values(?,?),"tom",5000); System.out.println(row); }我们可以将jdbcTemplate的创建全交给Spring,将数据源DataSource的创建权交给Spring,在Spring容器内部将数据源DataSource注入到jdbcTemplate模板对象中,配置如下:
<?xml version="1.0" encoding="UTF-8"?> <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="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="user" value="root"/> <property name="password" value="1121"/> </bean> <!--jdbc模板对象--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>@Test //测试Spring产生JdbcTemplate对象 public void test2()throws Exception{ ApplicationContext context = new ClassPateXmlApplicationContext("applicationContext.xml"); JdbcTemplate jdbcTemplate = new() context.getBean("jdbcTemplate",JdbcTemplate.class); int cont = jdbcTemplate.Update("insert into account values(?,?),"zhangsan",500); System.out.println(cont) }- jdbc.properties
<!--加载jdbc.properties--> <context:property-placeholder location="classpath:jdbc.properties"/>-
$
-
执行数据库操作
-
更新操作:
jdbcTemplate.update(sql,params)
-
查询操作
jdbcTemplate.query(sql,Mapper,params)
jdbcTemplate.queryForObject(sql,Mapper,params)
-

浙公网安备 33010602011771号