1. 程式人生 > >Java框架學習_Spring(六)Spring_Dao層解決方案:JDBC模板的配置、模板的CRUD操作

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);
	}

}