Spring中利用JDBC模板完成SQLServer資料庫(MySQL一樣)各種操作
阿新 • • 發佈:2019-01-26
一、匯入jar包
這裡的包是測試類的包
這裡是Spring需要的各種包
二、配置檔案db.property
jdbcUser=資料庫的使用者名稱(中文地方自己填寫)
jdbcPassword=資料庫的密碼
jdbcDriver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbcUrl=jdbc\:sqlserver\://127.0.0.1\:1433;databaseName\= 資料庫名字
initPoolSize=5
maxPoolSize=10
三、Spring bean configuration File檔案的配置
在這裡名字為Application-Context.xml
建立此檔案的時候,匯入名稱空間bean、context、jdbc
<?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:jdbc="http://www.springframework.org/schema/jdbc"
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-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd" >
<!-- 匯入資原始檔 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置C3P0資料來源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbcUser}"></property>
<property name="password" value="${jdbcPassword}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${jdbcDriver}"></property>
<property name="initialPoolSize" value="${initPoolSize}"></property>
<property name="maxPoolSize" value="${maxPoolSize}"></property>
</bean>
<!-- 配置Spring的JDBCTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref="dataSource"></property>
</bean>
</beans>
四、建立測試.java檔案
檔名:JDBCTest.java
private ApplicationContext ctx = null;
private JdbcTemplate jdbcTemplate = null;
{
//建立spring容器
ctx = new ClassPathXmlApplicationContext("Application-Context.xml");
jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
}
五、初始化資料庫
建立資料庫
create database Spring
建表
create table department(
id varchar(10) not null,
name varchar(10) not null,
primary key(id)
)
create table student(
id varchar(10) not null,
name varchar(10) not null,
sex char(2) check(sex='男' or sex='女'),
departmentId varchar(10),
primary key(id),
foreign key(departmentId) references department(id)
)
插入department表資料
插入student表資料
六、利用DataSource嘗試連線SQLServer資料庫
/**
* 利用DataSource連線資料
*/
@Test
public void test(){
//獲取DataSource例項
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
try {
//連線資料庫
dataSource.getConnection();
System.out.println("連線成功");
} catch (SQLException e) {
System.out.println("連線失敗");
}
}
結果為:(顯示資料庫連線成功,確保資料庫之前可以正常工作)
七、利用JdbcTemplate,更新資料庫
/**
*更新資料庫資料
*可以執行insert,delete,update語法
*/
@Test
public void testUpdate(){
String sql = "update student set name=? where id=?";
jdbcTemplate.update(sql, "小黃","8000114001");
}
結果為;
八、批量更新資料庫
/**
* 執行批量更新:批量的Insert、update,delete
* batchArgs是一個List集合,而集合中是陣列,這樣可以實現批量新增資料
*/
@Test
public void testBatchUpdate(){
String sql = "insert into student(id,name,departmentId) values(?,?,?)";
List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[]{"8000114004","小賴","4"});
batchArgs.add(new Object[]{"8000114005","小浩","1"});
batchArgs.add(new Object[]{"8000114006","小陳","2"});
batchArgs.add(new Object[]{"8000114007","小張","3"});
batchArgs.add(new Object[]{"8000114008","小王","4"});
jdbcTemplate.batchUpdate(sql, batchArgs);
}
結果為:
九、建兩個基本的類
student.java
package com.hui.spring.jdbc;
public class Student {
private String id;
private String name;
private String sex;
private Department department;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + sex + ", department=" + department + "]";
}
}
Department.java
package com.hui.spring.jdbc;
public class Department {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department [id=" + id + ", name=" + name + "]";
}
}
十、從資料庫中獲取資料填充student物件
/**
* 從資料庫獲取物件
* 注意的是:此處用的方法不是JdbcTemplate.queryForObject(String sql, Class<Student> requiredType, Object... args)
* 需要呼叫JdbcTemplate.queryForObject(String sql, RowMapper<Student> rowMapper, Object... args)
* 1、其中的RowMapper指定如何去對映結果集的行,常用的實現類為BeanPropertyRowMapper
* 2、使用SQL中列的別名(資料庫中的列名不符合類的成員變數時,使用別名)去進行對映
* 3、不支援級聯屬性,即依賴物件不能夠通過此實現
*/
@Test
public void testQueryForObject(){
String sql = "select id , name , sex from student where id = ?";
RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
Student student = jdbcTemplate.queryForObject(sql, rowMapper, "8000114001");
System.out.println(student);
}
結果為:
十一、利用條件查詢語句,獲取例項集合,即多個符合條件的student物件的集合
/**
* 條件查詢語句,得到實體類集合
* 注意呼叫的不是queryForList
*/
@Test
public void testQueryForList(){
String sql = "select id , name , sex from student where id != ?";
RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
List<Student> students = jdbcTemplate.query(sql, rowMapper, "8000114001");
System.out.println(students);
}
結果為:
十二、用條件查詢,獲取單個值
/*
* 獲取單個值
*/
@Test
public void testQueryForObjectValue(){
String sql = "select count(*) from student";
//過時方法
//long count = jdbcTemplate.queryForLong(sql);
long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
結果為:
這就是利用JdbcTemplate進行資料庫各種操作的簡單示例。
後加:
十三、在 JDBC 模板中使用具名引數
Application-Context.xml檔案中加入以下內容:
<!-- 配置NamedParameterJdbcTemplate,該物件可以使用具名引數,其沒有無引數的構造器 ,所以必須為構造器指定引數-->
<bean id = "namedParameterJdbcTemplate"
class = "org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>寫程式碼片
具名引數的使用一:
/**
* 具名引數,可以為引數起名字
* 1、好處:若有多個引數,則不用再去對應位置,直接對應名字,便於維護
* 2、缺點:較為麻煩
*/
@Test
public void testNameParameterJdbcTemplate(){
String sql = "insert into student(id,name,sex) values(:id,:name,:sex)";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", "8000114009");
paramMap.put("name", "小鵬");
paramMap.put("sex", "男");
namedParameterJdbcTemplate.update(sql, paramMap);
}
//結果是資料中添加了上述資料
具名引數的使用二:
/**
* 使用具名引數時,可以使用update(String sql,SqlParameterSource)方法進行更新操作
* 1、SQL語句中的引數名和類的屬性一致
* 2、使用SqlParameterSource的BeanPropertySqlParameterSource實現類作為引數。
*/
@Test
public void testNamedParameterJdbcTemplate2(){
String sql = "insert into student(id,name,sex) values(:id,:name,:sex)";
Student student = new Student();
student.setId("8000114010");
student.setName("小敏");
student.setSex("女");
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(student);
namedParameterJdbcTemplate.update(sql, paramSource);
}
//結果是資料中添加了上述資料
十四、進行資料庫事務操作(原子性操作)
如下流程(簡述):
1、加入AOP(面向切面程式設計)的jar包
2、匯入tx名稱空間
1、在Application-Context.xml檔案中加入以下內容:
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 啟用事務註解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
在所需要進行事務操作的方法上添加註釋:
//加了此註釋,才可以進行事務操作
@Trasactional
public 返回值 方法名(args)
{
}