一、關於JdbcTemplate
JdbcTemplate是最基本的Spring JDBC模板,這個模板支持簡單的JDBC數據庫訪問功能以及基於索引參數的查詢。
Spring數據訪問模板:在數據庫操作過程中,有很大一部分重復工作,比如事務控制、管理資源以及處理異常等,Spring的模板類處理這些固定部分。同時,應用程序相關的數據訪問在回調的實現中處理,包括語句、綁定參數以及整理結果等。這樣一來,我們只需關心自己的數據訪問邏輯即可。
Spring的JDBC框架承擔了資源管理和異常處理的工作,從而簡化了JDBC代碼,我們只需要編寫從數據庫讀寫數據的必需代碼就萬事大吉了。
二、Spring JdbcTemplate實例
我們的學習目標就是動手寫一個demo,實現對Category的CRUD操作。
1.創建表
mysql新建數據庫store,然后執行如下sql:
create table Category ( Id int not null, Name varchar(80) null, constraint pk_category primary key (Id) ); INSERT INTO category(id,Name) VALUES (1,'女裝'); INSERT INTO category(id,Name) VALUES (2,'美妝'); INSERT INTO category(id,Name) VALUES (3,'書籍');
2.我用的IDE是IdeaIU,通過maven構建項目,通過xml配置spring。完成后的代碼結構為:
3.創建實體類Category
public class Category{
private int cateId;
private String cateName;
public int getCateId() {
return cateId;
}
public void setCateId(int cateId) {
this.cateId = cateId;
}
public String getCateName() {
return cateName;
}
public void setCateName(String cateName) {
this.cateName = cateName;
}
@Override
public String toString() {
return "id="+cateId+" name="+cateName;
}
}
4.修改pom.xml,引入相關依賴。
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- Mysql數據庫鏈接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
<scope>runtime</scope>
</dependency>
</dependencies>
5.配置applicationContext.xml
需要配置dataSource作為jdbcTemplate的數據源。然后配置CategoryDao bean,構造注入了jdbcTemplate對象。完整的applicationContext.xml如下:
<?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="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/store"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="categoryDao" class="CategoryDao">
<constructor-arg ref="jdbcTemplate"></constructor-arg>
</bean>
</beans>
6.數據訪問實現類CategoryDao
CategoryDao構造函數包含了參數jdbcTemplate,然后實現了常用的數據訪問操作。可以看到,我們只要關注具體的sql語句就可以了。另外,在getById()和getAll()方法中使用了lambda語法。
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* Created by 陳敬 on 2017/6/6.
*/
public class CategoryDao {
private JdbcTemplate jdbcTemplate;
public CategoryDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int add(Category category) {
String sql = "INSERT INTO category(id,name)VALUES(?,?)";
return jdbcTemplate.update(sql, category.getCateId(), category.getCateName());
}
public int update(Category category) {
String sql = "UPDATE Category SET Name=? WHERE Id=?";
return jdbcTemplate.update(sql, category.getCateName(), category.getCateId());
}
public int delete(int id) {
String sql = "DELETE FROM Category WHERE Id=?";
return jdbcTemplate.update(sql, id);
}
public int count(){
String sql="SELECT COUNT(0) FROM Category";
return jdbcTemplate.queryForObject(sql,Integer.class);
}
public Category getById(int id) {
String sql = "SELECT Id,Name FROM Category WHERE Id=?";
return jdbcTemplate.queryForObject(sql, (ResultSet rs, int rowNumber) -> {
Category category = new Category();
category.setCateId(rs.getInt("Id"));
category.setCateName(rs.getString("Name"));
return category;
}, id);
}
public List<Category> getAll(){
String sql="SELECT Id,Name FROM Category";
List<Category> result=jdbcTemplate.query(sql, (resultSet, i) -> {
Category category = new Category();
category.setCateId(resultSet.getInt("Id"));
category.setCateName(resultSet.getString("Name"));
return category;
});
return result;
}
}
7.測試
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class testCategoryDao {
@Autowired
private CategoryDao categoryDao;
@Test
public void testAdd() {
Category category = new Category();
category.setCateId(4);
category.setCateName("母嬰");
int result = categoryDao.add(category);
System.out.println(result);
}
@Test
public void testUpdate() {
Category category = new Category();
category.setCateId(4);
category.setCateName("男裝");
int result = categoryDao.update(category);
System.out.println(result);
}
@Test
public void testGetById() {
int id = 4;
Category category = categoryDao.getById(id);
System.out.println(category.toString());
}
@Test
public void testGetAll() {
List<Category> categories = categoryDao.getAll();
for (Category item : categories) {
System.out.println(item);
}
}
@Test
public void testCount() {
int count = categoryDao.count();
System.out.println(count);
}
@Test
public void testDelete() {
int id = 4;
int result = categoryDao.delete(id);
System.out.println(result);
}
}
完整代碼:https://github.com/cathychen00/learnjava/tree/master/DemoJdbcTemplate


