springJDBC模板

spring的jdbc模板的使用

入门项目案例

需要使用的jar包

  • 基本的6个jar包(开发spring必须的包)
  • 数据库驱动包
  • springjdbc模板的jar

使用jdbc模板来保存数据

package top.toplovelypig.demo;

import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class demo1 {

	@Test
	public void demo1() {
		//创建连接池
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///test");
		dataSource.setUsername("root");
		dataSource.setPassword("admin");
		//创建jdbc模板
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.update("insert into account values(null, ?, ?)", "hello", 1220d);
		
	}
}

使用springjdbc模板主要就是有两步

  • 第一步就是创建连接池,
  • 第二步就是创建jdbc模板,然后通过模板就可以执行对数据库的操作了

将连接池和模板交给spring来管理

上面的案例中无论是创建连接池还是创建jdbc模板都是使用new的方式来自己创建对象,这一步可以通过springioc来优化一下。

配置文件

<?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"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!--配置spring的内置连接池  -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!-- 属性注入 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql:///test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="admin"></property>
	</bean>
	
	<!-- 配置spring的jdbc模板 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
</beans>

测试代码

package top.toplovelypig.demo;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo2 {
	
	@Resource(name="jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Test
	public void demo2() {
		jdbcTemplate.update("insert into account values(null, ?, ?)", "nice", 2300L);
	}
}

<font color="red">需要注意的是对于spring4或者5的版本使用spring的jdbc模板时需要加上spring-aop的包,否则就是出现如下所示的错误:</font>

java.lang.NoClassDefFoundError: org/springframework/aop/TargetSource
...
Caused by: java.lang.ClassNotFoundException: org.springframework.aop.TargetSource

使用开源的数据库连接池

DBCP的使用

需要引入的jar包

apache.commons.dbcp
apache.commons.pool

配置文件

<?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"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!--配置spring的内置连接池  -->
	<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		属性注入
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql:///test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="admin"></property>
	</bean> -->
	
	<!-- 配置dbcp连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql:///test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="admin"></property>
	</bean>
	
	<!-- 配置spring的jdbc模板 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>

测试文件和使用默认的连接池的时候是一样的。

c3p0的使用

jar包

com.springsource.com.mchange.v2.c3p0的jar

c3p0的配置

<!--配置c3p0连接池的配置-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver" />
    <property name="jdbcUrl" value="jdbc:mysql:///test" />
	<property name="user" value="root" />
    <property name="password" value="admin" />
</bean>

抽取配置到属性文件

定义一个属性文件

jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.username=root
jdbc.password=admin

在spring的配置文件中引入属性文件

  • 第一种方式是通过一个bean标签引入

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="location" value="classpath:jdbc.properties"></property>
    </bean>
    
  • 第二种方式

    <context:property-placeholder location="classpath:jdbc.properties"/>
    

配置属性文件中的值

<!--配置C3PO连接池===============================-->
<bean id="dataSource"class="com.mchange.V2.c3pe.ComboPooledDatasource">
    <property name="driverClass"value="${jdbc.driverclass}"/>
    <property name="jdbcUrL"value="${jdbc.url}"/>
    <property name="user"value="${jdbc.username}"/>
    <property name="password"value="${jdbc.password}"/>
</bean>

使用jdbc模板完成查询的操作

对于增删改都是差不多的操作,主要需要注意的还是查询的操作。

查询某一个字段

@Test
//查询操作:
public void demo4(){
    String name =jdbcTemplate.queryForObject("select name from account where id =?",string.class,5);
    System.out.print1n(name);
}

查询数量

@Test
//统计查询
public void demo5(){
    Long count =jdbcTemplate.queryForobject("select count(*)from account",Long.class);
    System.out.println(count);
}

将查询的一条数据封装到一个对象中

对象的代码

public class Account{
    private int id;
    private String name;
    private Double money;
    //省略了set、get方法
}

测试代码

@Test
//封装到一个对象中
public void demo6(){
    Account account=jdbcTemplate.queryForObject("select*from account where id=?",new MyRowMapper(),5);
    System.out.printin(account);
}

这里的第二个参数是需要一个自定义类的对象,这个类是需要我们自己去定义的,并且该类需要实现RowMapper<T>,自己定义的这个类可以直接与dao写在同一个类里面即可(java中一个类是可以写在一个类的里面的)

class MyRowMapper implements RowMapper<Account>{
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException{
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getDouble("money"));
        return account;
    }
}

将查询结果封装到list

上面是查询一个记录将其封装到一个对象中,需要自己定义转换类(将结果集取出来封装到对象中),对于查询单结果需要封装到多个对象中时也是一样的,只是使用的方法不同而已,那个自定义的类还是一样的。

@Test
//查询多条记录
public void demo7(){
	List<Account>iist=jdbcTemplate.query("select*from account",new MyRowMapper());
    for(Account account:list){
		System.out.println(account);
    }
}

这里的query方法的第二个参数依然是上面的那个自定义类的对象。

转载于:https://my.oschina.net/guowei11/blog/3077581

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值