Java框架学习_Spring(六)Spring_Dao层解决方案:JDBC模板的配置、模板的CRUD操作

Spring在Dao层的解决方案,采用JDBC模板和数据库交换数据

导包:Spring_jdbc模板相关jar包


按照之前学JDBC的步骤,创建连接并交给Spring管理(这里是用xml配置的方式):

  1. 配置原始连接(就是自带的链接,没有用到连接池)
  2. 配置DBCP版连接池
  3. 配置c3p0版连接池
  4. 将连接信息单独放到properties文件里面进一步解耦和

==========================================================

  1. 先创建原始连接
package cn.nupt;

import java.util.Map;

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

public class Spring_JDBC_demo01 {
	@Test
	public void test01() {

		// 创建普通版连接池
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///mybatis");
		dataSource.setUsername("root");
		dataSource.setPassword("1111");

		// 创建JDBC模板
		JdbcTemplate template = new JdbcTemplate(dataSource);
		template.update("insert into user values (null,?,?,?,?)", "程奕迅", "2019-2-2", 1, "哈尔滨");

	}

}
  1. 将这个连接交给Spring的xml文件管理(这里直接配置了原始连接、DBCP版连接池、c3p0版连接池,按照自己的数据库该相应的用户名、密码就行了)
<?xml version="1.0" encoding="utf-8"?>
<beans 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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">



<!-- 配置普通版连接池========================= -->
<!-- 

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///mybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="1111"></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:///mybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="1111"></property>

</bean>
 -->




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

</bean>



<!-- 配置JDBC模板的 ================================-->
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>

</bean>


</beans>

更近一步,将配置单独放到一个jdbc.properties文件里面:

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///mybatis
jdbc.user=root
jdbc.password=1111

然后在xml中引入这个properties配置文件,然后在出c3p0连接池里面引用相应的变量,也能达到同样的效果(变成动态的配置):

<!-- 配置文件放到properties方式一=============================== -->

<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"></property>
</bean> -->

<!-- 配置文件放到properties方式二:常用=============================== -->
 
<context:property-placeholder location="classpath:jdbc.properties"/>




<!-- 配置C3P0版连接池========================= -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>

</bean>

最后,编写测试类:

package cn.nupt.test;

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 JdbcTest {
	@Resource(name="template")
	private JdbcTemplate template;
	
	
	@Test
	public void test() {
		template.update("insert into user values (null,?,?,?,?)","海贼黑胡子","2019-2-2" ,1,"东海" );
	
	}
	
	
	//上面用到了junit和aop的整合,这里是原始的
	
	/*
	@Test
	public void test() {
		
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		//根据ID找到相应的类
		JdbcTemplate  template = (JdbcTemplate) applicationContext.getBean("template");
		template.update("insert into user values (null,?,?,?,?)","程bingbing","2019-2-2" ,1,"哈滨" );
	}
	*/
}

2、模板的CRUD操作:
模板的增删改查操作中,只有查询比较特殊,下面在前面已经配置好的情况下写几种查询情况(最主要的是RowMapper这个接口的用法,一如JDBC中的ResultHandler)

  1. 插入数据,增删改都是一样的,在这里就不一一演示了
  2. 查询一群人(输出一个集合)
  3. 查询一个人(输出一个Bean)
  4. 查询一个人的一个属性,比如name
  5. 统计查询(聚合函数)

具体演示代码如下:

package cn.nupt.test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import javax.swing.tree.TreePath;

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

import cn.nupt.domain.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTest {
	@Resource(name = "template")
	private JdbcTemplate template;

	@Test
	//插入数据,增删改都是一样的,在这里就不一一演示了
	public void test01() {
		template.update("insert into user values (null,?,?,?)", "海贼白胡子", "2019-2-2", "东海");
	}

	@Test
	//查询一群人
	public void test02() {

		List<User> list = template.query("select * from user", new RowMapper<User>() {

			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setAddress(rs.getString("address"));
				user.setBirthday(rs.getDate("birthday"));
				user.setUsername(rs.getString("username"));

				return user;
			}

		});

		for (User user : list) {
			System.out.println(user);
		}
	}

	@Test
	//查询一个人
	public void test03() {
		User user = template.queryForObject("select * from user where id = ? ", new RowMapper<User>() {

			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setAddress(rs.getString("address"));
				user.setBirthday(rs.getDate("birthday"));
				user.setUsername(rs.getString("username"));

				return user;
			}

		}, 46);

		System.out.println(user);

	}
	
	
	@Test
	//查询一个人的一个属性,比如name
	public void test04() {
		String name =  template.queryForObject("select username from user where id = ?",String.class,46);
		System.out.println(name);
	}
	
	@Test
	//统计查询
	public void test05() {
		long num =  template.queryForObject("select count(*) from user ",long.class);
		System.out.println(num);
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值