Spring4.x學習筆記——JdbcTemplate基礎操作
阿新 • • 發佈:2019-01-02
一、相關概念
spring是一個一站式的框架,對不同持久層的技術都進行了封裝(處理資料庫技術,基本的crud操作即增刪改查),如JDBC、Hibermate、MaBatis、JPA等。
二、spring對JDBC的封裝使用步驟大體如下:
- 匯入jar包 spring-jdbc、spring-tx
- 建立DriveManagerDataSource物件,對資料庫進行配置
- className
- url
- username
- password
- 建立JdbcTemplate物件
- 注入dataSource物件
- 呼叫JdbcTemplate封裝的方法進行sql操作
- update(String sql , Object…arr) //增刪改
- queryForObject(String sql , RowMapper rowMapper , Object…arr); //查詢,單個值或物件
- query(String sql , RowMapper rowMapper , Object…arr); //查詢 ,list
- 查詢方法的形參需要一個實現RowMapper介面的類,對資料進行封裝,詳見以下例項
三、利用spring的jdbcTemplate實現簡單的sql操作例項
1、建立工程,引入相關jar包
2、建立spring配置檔案並寫必要約束
<?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"
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" >
</beans>
3、建表、配置資料庫及jdbcTemplate
- 建立一個簡單的book表
- 建立DataSource.properties
#DataSource.properities
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/spring_jdbc_template_test?characterEncoding=UTF-8&useOldAliasMetadataBehavior=true
username=root
password=123456
- spring配置:
<!-- 掃描包下的所有註解 -->
<context:component-scan base-package="com.jdbctemplate.book"></context:component-scan>
<context:property-placeholder location="resource/DataSource.properties"></context:property-placeholder>
<!-- 建立DataSource物件 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 建立JdbcTemplate物件 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
4、建立Book例項類,儲存從資料庫取出的資料
public class Book {
private String name;
private float prive;
public Book() {
super();
}
public Book(String name, float prive) {
super();
this.name = name;
this.prive = prive;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrive() {
return prive;
}
public void setPrive(float prive) {
this.prive = prive;
}
@Override
public String toString() {
return "Book [name=" + name + ", prive=" + prive + "]";
}
}
4、寫dao層介面
public interface BookDao {
/**
* 新增圖書
* @param name
* @param price
* @return
*/
public int addBook(String name , float price);
/**
* 刪除圖書
* @param name
* @return
*/
public int delBook(String name);
/**
* 修改價格
* @param name
* @param price
* @return
*/
public int updateBook(String name,float price);
/**
* 返回所有Book資訊
* @return
*/
public List<Book> getAllBook();
/**
* 返回指定書名的圖書資訊
* @param name
* @return
*/
public Book getBook(String name);
/**
* 返回指定書名的價格
* @param name
* @return
*/
public float getPrice(String name);
}
5、寫BookDao的實現類,並配置
public class BookDaoImpl implements BookDao{
// jdbc模板
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
public int addBook(String name, float price) {
return jdbcTemplate.update("insert into book value(?,?)",name,price);
}
public int delBook(String name) {
return jdbcTemplate.update("delete from book where name=?",name);
}
public int updateBook(String name, float price) {
return jdbcTemplate.update("update book set price=? where name=?",price,name);
}
public List<Book> getAllBook() {
return jdbcTemplate.query("select * from book", new BookRowMapper());
}
public Book getBook(String name) {
return jdbcTemplate.queryForObject("select * from book where name=?", new BookRowMapper(),name);
}
public float getPrice(String name) {
return jdbcTemplate.queryForObject("select price from book where name=?", Float.class);
}
private class BookRowMapper implements RowMapper<Book>{
@Override
public Book mapRow(ResultSet re, int arg1) throws SQLException {
return new Book(re.getString("name"),re.getShort("price"));
}
}
}
<bean id="bookDaoImpl" class="com.jdbctemplate.book.dao.impl.BookDaoImpl"></bean>
6、寫BookService類
public class BookService {
@Resource(name="bookDaoImpl")
private BookDaoImpl bookDaoImpl;
public List<Book> getAll() {
return bookDaoImpl.getAllBook();
}
public Book get(String name) {
return bookDaoImpl.getBook(name);
}
public float getPrice(String name) {
return bookDaoImpl.getPrice(name);
}
public int add(String name,float price) {
return bookDaoImpl.addBook(name, price);
}
public int delet(String name) {
return bookDaoImpl.delBook(name);
}
}
<!-- 建立BookService物件 -->
<bean id="bookService" class="com.jdbctemplate.book.service.BookService"></bean>
7、寫測試類
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("resource/spring.xml");
BookService bookService = (BookService) context.getBean("bookService");
bookService.add("數學", 23.5F);
bookService.add("語文", 20.5F);
System.out.println(bookService.getAll());
}
}
四、在過程中@Resource無法使用解決
在過程中註解@Resource無法使用,import javax.annotation.Resource;也一直紅線無法引入,改變JDK版本後奇怪的就好了,但專案中沒有錯誤,專案上總有個紅叉。解決:右鍵專案–properties–project Facets–java對於的版本改統一即可