Spring的jdbcTemplate使用學習筆記,簡化我們對資料庫的操作
技術標籤:Spring學習筆記javaspring
之前也說過spring框架對於每一層都有解決方案,對於持久層也提供瞭解決方案:ORM模組和JDBC的模板。接下來通過一個小案例先了解一下JDBC模板的簡單使用。
準備工作:因為持久層是對資料庫操作,我們要先建立一個數據庫表,自己可以隨意建立一個數據庫表,我建立的是account資料表:
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`name` varchar(255) NOT NULL COMMENT '使用者名稱',
`money` float NOT NULL COMMENT '金額',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
建立一個maven工程,在pom檔案中新增以下座標:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
根據自己的習慣在maven工程中建立一個包,再建立一個類,寫一個main函式。我寫的具體如下:
public class JdbcTemplateDemo {
public static void main(String[] args) {
//建立資料來源
DriverManagerDataSource dm = new DriverManagerDataSource();
//設定資料庫連線資訊
dm.setDriverClassName("com.mysql.jdbc.Driver");
dm.setUrl("jdbc:mysql://localhost:3306/stu");
dm.setUsername("root");
dm.setPassword("123456");
//建立JdbcTemplate物件
JdbcTemplate jt = new JdbcTemplate(dm);
//執行sql語句
jt.update("insert into account(name,money) value (?,?)","小八","1000");
//jt.execute("insert into account(name,money) value ('小五',1000)");
}
}
執行結果就是往我們建立的資料庫中新增一條資料。以上就是spring中的JDBC模板的簡單使用。上面程式碼還是有問題的,我們既然學習了springIoc容器通過觀察上面的程式碼發現建立資料來源和JdbcTemplate模板的建立都是通過new出來的,資料庫連線資訊是通過set方法設定的,這些都是可以通過springIoc容器來解決。接下來我改造上面程式碼。
建立一個bean.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">
<!--配置資料來源,我在這使用的是spring框架中的內建的資料來源,其實也可以使用c3p0,dbcp,durid資料庫連線池-->
<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/stu"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--配置jdbcTemplate模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>
我們再寫一個main方法:
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//載入bean.xml檔案
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//獲取jdbcTemplate模板的bean物件
JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");
//執行sql語句
jt.update("insert into account(name,money) value (?,?)", "小九", "1000");
}
}
以上就是我們改造完後的程式碼,接下來我在dao中具體使用JdbcTemplate寫幾個方法執行看看結果。
Account實體類:
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
//get/set方法別忘記生成
//toString方法也別忘記生成
}
AccountDao介面:
public interface AccountDao {
/**
* 查詢所有使用者
*/
List<Account> findAll();
/**
* 根據id查詢使用者
*/
Account findAccountById(Integer accountId);
/**
* 根據使用者名稱查詢使用者
*/
Account findAccountByName(String accountName);
/**
* 更新賬戶
*/
void updateAccount(Account account);
/**
* 刪除賬戶
*/
void deleteAccountById(Integer accountId);
}
AccountDaoImpl介面實現類:
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Account> findAll() {
List<Account> list = jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
return list;
}
public Account findAccountById(Integer accountId) {
List<Account> list = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
return list.isEmpty() ? null : list.get(0);
}
public Account findAccountByName(String accountName) {
List<Account> list = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
if (list.isEmpty()){
return null;
}else if (list.size() > 1){
throw new RuntimeException("結果集不唯一");
}
return list.get(0);
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name = ? , money = ? where id = ?", account.getName(),account.getMoney(),account.getId());
}
public void deleteAccountById(Integer accountId) {
jdbcTemplate.update("delete from account where id = ?" , accountId);
}
}
main方法執行看結果:
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
AccountDao jt = (AccountDao) context.getBean("accountDao");
//查詢所用賬戶資訊
List<Account> lists = jt.findAll();
for (Account list : lists){
System.out.println(list);
}
}
}
查詢結果:
根據id查詢一個賬戶:
Account account = jt.findAccountById(4);
System.out.println(account);
執行結果:
其他幾個方法我就不演示了,如有不懂的可以給我留言。
在AccountDaoImpl 實現類中都有這幾行程式碼,不同的持久層都要寫下面的程式碼顯的比較麻煩:
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
//可以通過繼承JdbcDaoSupport類來解決這個問題
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
/*private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}*/
public List<Account> findAll() {
List<Account> list = super.getJdbcTemplate().query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
return list;
}
//其他幾個方法我就不寫了,也就改了super.getJdbcTemplate()這個程式碼
}
關於繼承JdbcDaoSupport 和自己在dao寫JdbcTemplate 模板兩者具體有什麼區別?區別在於我們通過繼承的話就不能通過註解來開發了,因為這些程式碼在spring框架中我們不可以修改的,只能使用xml方式。在dao中定義JdbcTemplate的方式,xml和註解方式都可以使用。
當然我們在這只是使用xml方式,註解方式也是可以的。我們要在bean.xml中開啟註解掃描
<!--開啟註解掃描-->
<context:component-scan base-package="com.zy.jdbcTemplate.dao"></context:component-scan>
修改AccountDaoImpl實現類,添加註解:
@Repository("accountDao")
public class AccountDaoImpl /*extends JdbcDaoSupport*/ implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//......
}
加油吧!!!