Spring DAO之JDBC

Spring提供的DAO(數據訪問對象)支持主要的目的是便于以標準的方式使用不同的數據訪問技術, 如JDBC,Hibernate或者JDO等。它不僅可以讓你方便地在這些持久化技術間切換, 而且讓你在編碼的時候不用考慮處理各種技術中特定的異常。
為了便于以一種一致的方式使用各種數據訪問技術,如JDBC、JDO和Hibernate, Spring提供了一套抽象DAO類供你擴展。這些抽象類提供了一些方法,通過它們你可以 獲得與你當前使用的數據訪問技術相關的數據源和其他配置信息。
Dao支持類:
JdbcDaoSupport - JDBC數據訪問對象的基類。 需要一個DataSource,同時為子類提供 JdbcTemplate。
HibernateDaoSupport - Hibernate數據訪問對象的基類。 需要一個SessionFactory,同時為子類提供 HibernateTemplate。也可以選擇直接通過 提供一個HibernateTemplate來初始化, 這樣就可以重用后者的設置,例如SessionFactory, flush模式,異常翻譯器(exception translator)等等。
JdoDaoSupport - JDO數據訪問對象的基類。 需要設置一個PersistenceManagerFactory, 同時為子類提供JdoTemplate。
JpaDaoSupport - JPA數據訪問對象的基類。 需要一個EntityManagerFactory,同時 為子類提供JpaTemplate。
本節主要討論Sping對JdbcDaoSupport的支持。
下面是個例子:
drop?table?if?exists?user;?

/*==============================================================*/?
/* Table: user??????????????????????????????????????????????????*/?
/*==============================================================*/?
create?table?user?
(?
?? id???????????????????bigint?AUTO_INCREMENT?not?null,?
???name?????????????????varchar(24),?
?? age??????????????????int,?
???primary?key?(id)?
);
public?class?User {?
????private?Integer id;?
????private?String name;?
????private?Integer age;?

????public?Integer getId() {?
????????return?id;?
????}?

????public?void?setId(Integer id) {?
????????this.id = id;?
????}?

????public?String getName() {?
????????return?name;?
????}?

????public?void?setName(String name) {?
????????this.name = name;?
????}?

????public?Integer getAge() {?
????????return?age;?
????}?

????public?void?setAge(Integer age) {?
????????this.age = age;?
????}?
}
/**?
* Created by IntelliJ IDEA.<br>?
* <b>User</b>: leizhimin<br>?
* <b>Date</b>: 2008-4-22 15:34:36<br>?
* <b>Note</b>: DAO接口?
*/?
public?interface?IUserDAO {?
????public?void?insert(User user);?

????public?User find(Integer id);?
}
import?javax.sql.DataSource;?
import?java.sql.Connection;?
import?java.sql.SQLException;?

/**?
* Created by IntelliJ IDEA.<br>?
* <b>User</b>: leizhimin<br>?
* <b>Date</b>: 2008-4-22 13:53:56<br>?
* <b>Note</b>: 基類DAO,提供了數據源注入?
*/?
public?class?BaseDAO {?
????private?DataSource dataSource;?

????public?DataSource getDataSource() {?
????????return?dataSource;?
????}?

????public?void?setDataSource(DataSource dataSource) {?
????????this.dataSource = dataSource;?
????}?

????public?Connection getConnection() {?
????????Connection conn =?null;?
????????try?{?
????????????conn = dataSource.getConnection();?
????????}?catch?(SQLException e) {?
????????????e.printStackTrace();?
????????}?
????????return?conn;?
????}?
}
/**?
* Created by IntelliJ IDEA.<br>?
* <b>User</b>: leizhimin<br>?
* <b>Date</b>: 2008-4-22 15:36:04<br>?
* <b>Note</b>: DAO實現?
*/?
public?class?UserDAO?extends?BaseDAO?implements?IUserDAO {?

????public?JdbcTemplate getJdbcTemplate(){?
????????return?new?JdbcTemplate(getDataSource());?
????}?
????public?void?insert(User user) {?
????????String name = user.getName();?
????????int?age = user.getAge().intValue();?

//????????jdbcTemplate.update("INSERT INTO user (name,age) "?
//????????????????+ "VALUES('" + name + "'," + age + ")");?

????????String sql =?"insert into user(name,age) values(?,?)";?
????????getJdbcTemplate().update(sql,new?Object[]{name,age});?
????}?

????public?User find(Integer id) {?
????????List rows = getJdbcTemplate().queryForList(?
????????????????"SELECT * FROM user WHERE id="?+ id.intValue());?

????????Iterator it = rows.iterator();?
????????if?(it.hasNext()) {?
????????????Map userMap = (Map) it.next();?
????????????Integer i =?new?Integer(userMap.get("id").toString());?
????????????String name = userMap.get("name").toString();?
????????????Integer age =?new?Integer(userMap.get("age").toString());?

????????????User user =?new?User();?

????????????user.setId(i);?
????????????user.setName(name);?
????????????user.setAge(age);?

????????????return?user;?
????????}?
????????return?null;?
????}?
}
<?xml?version="1.0"?encoding="UTF-8"?>?
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"?
????????"http://www.springframework.org/dtd/spring-beans.dtd">?

<beans>?
????<bean?id="dataSource"?
??????????class="org.apache.commons.dbcp.BasicDataSource"?singleton="true">?
????????<property?name="driverClassName">?
????????????<value>com.mysql.jdbc.Driver</value>?
????????</property>?
????????<property?name="url">?
????????????<value>jdbc:mysql://localhost:3306/springdb</value>?
????????</property>?
????????<property?name="username">?
????????????<value>root</value>?
????????</property>?
????????<property?name="password">?
????????????<value>leizhimin</value>?
????????</property>?
????</bean>?

????<bean?id="baseDAO"?class="com.lavasoft.springnote.ch05_jdbc03_temp.BaseDAO"?abstract="true">?
????????<property?name="dataSource">?
????????????<ref?bean="dataSource"/>?
????????</property>?
????</bean>?

????<bean?id="userDAO"?
??????????class="com.lavasoft.springnote.ch05_jdbc03_temp.UserDAO"?parent="baseDAO">?
????</bean>?

</beans>
import?org.springframework.context.ApplicationContext;?
import?org.springframework.context.support.FileSystemXmlApplicationContext;?

/**?
* Created by IntelliJ IDEA.<br>?
* <b>User</b>: leizhimin<br>?
* <b>Date</b>: 2008-4-22 15:59:18<br>?
* <b>Note</b>: 測試類,客戶端?
*/?
public?class?SpringDAODemo {?
????public?static?void?main(String[] args) {?
????????ApplicationContext context =?new?FileSystemXmlApplicationContext("D:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc03_temp\\bean-jdbc-temp.xml");?
????????User user =?new?User();?
????????user.setName("hahhahah");?
????????user.setAge(new?Integer(22));?
????????IUserDAO userDAO = (IUserDAO) context.getBean("userDAO");?
????????userDAO.insert(user);?
????????user = userDAO.find(new?Integer(1));?
????????System.out.println("name: "?+ user.getName());?
????}?
}
運行結果:
log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory).?
log4j:WARN Please initialize the log4j system properly.?
name: jdbctemplate?

Process finished with exit code 0

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273482.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273482.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273482.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

程序猿是如何解決SQLServer占CPU100%的

文章目錄 遇到的問題使用SQLServer Profiler監控數據庫 SQL1&#xff1a;查找最新的30條告警事件SQL2&#xff1a;獲取當前的總報警記錄數有哪些SQL語句會導致CPU過高&#xff1f;查看SQL的查詢計劃 選擇top記錄時&#xff0c;盡量為order子句的字段建立索引查看SQL語句CPU高的…

通過wifi調試Android程序

原文&#xff1a;http://www.cnblogs.com/sunzhenxing19860608/archive/2011/07/14/2106492.html 1.首先讓android手機監聽指定的端口&#xff1a;  這一步需要使用shell&#xff0c;因此手機上要有終端模擬器&#xff0c;不過網上很多&#xff0c;隨便找個就行了&#xff0c…

基于jQuery的對象切換插件:soChange 1.5 (點擊下載)

http://www.jsfoot.com/jquery/demo/2011-09-20/192.html 所有參數&#xff1a; $(obj).soChange({ thumbObj:null, //導航對象&#xff0c;默認為空 botPrev:null, //按鈕上一個&#xff0c;默認為空 botNext:null, //按鈕下一個。默認為空 thumbNowClass:no…

atitit.Oracle 9 10 11 12新特性attilax總結

atitit.Oracle 9 10 11 12新特性 1. ORACLE 11G新特性 1 1.1. oracle11G新特性 1 1.2. 審計 1 1.3. 1. 審計簡介 1 1.4. 其他&#xff08;大部分是管理功能&#xff09; 2 2. Oracle 12c 的 12 個新特性 2 2.1. 2 Improved Defaults 增強了DEFAULT, default目前可以直接指代…

mysql讀書筆記---mysql safe update mode

You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column 查看 mysql> show variables like %sql_safe%; 關閉 mysql> set sql_safe_updates0; 開啟 mysql> set sql_safe_updates1;

基于纖程(Fiber)實現C++異步編程庫(一):原理及示例

纖程&#xff08;Fiber&#xff09;和協程&#xff08;coroutine&#xff09;是差不多的概念&#xff0c;也叫做用戶級線程或者輕線程之類的。Windows系統提供了一組API用戶創建和使用纖程&#xff0c;本文中的庫就是基于這組API實現的&#xff0c;所以無法跨平臺使用&#xff…

MYSQL讀書筆記---運算符、字符串操作

運算符###########################################,!(<>),>,>,<,< is null , is not null, isnull(expr) expr between min and max expr in(v1,v2,...)流程#############################################mysql> select ifnull(1,0); #如果第一個參數為…

fluidity詳解

fluidity詳解 1.fluidity編譯過程 1.1.femtools庫調用方法 編譯fluidity/femtools目錄下所有文件&#xff0c;打包為libfemtools.a靜態庫文件&#xff1b;通過-lfemtools參數&#xff0c;并指定libfemtools.a靜態庫位置&#xff0c;即可調用 femtools 庫內所有函數2.fluidity主…

mysql讀書筆記---if語句

IF(expr1,expr2,expr3) 如果expr1是TRUE(expr1<>0 and expr1<>NULL)&#xff0c;則IF()的返回值為expr2;否則返回值則為expr3。IF()的返回值為數字值或字符串值&#xff0c;具體情況視其所在語境而定。 mysql>SELECT?IF(1>2,2,3); ->3 mysql>SELECT I…

C語言 將整數寫入內存指定的連續字節單元中

將整數數組寫入0x40003000開始的連續10個字節內存單元中&#xff0c;注意unsigned char *指向一個字節&#xff0c;而int *指向1個字&#xff08;4個字&#xff09;&#xff0c;但是可以把字中存儲的整數放入字節單元中&#xff0c;只要不超過表示的范圍&#xff0c;注意雖然un…

mysql讀書筆記----時間函數

1.獲得當前時間&#xff1a;時間格式yyyy-MM-dd curdate();2.DAYOFWEEK(date) 3.WEEKDAY(date) 4.DAYOFMONTH(date) 5.DAYOFYEAR(date) 6.MONTH(date) 7.DAYNAME(date) 8.MONTHNAME(date) 9.QUARTER(date) 10.WEEK(date) WEEK(date,first) 11.YEAR(date) 12.HOUR(time) 13.MINU…

企業數據1

1. 企業數據 1.1. 全局 1.1.1. 貨幣 CNY Chinese Yuan Renminbi &#xffe5; 6.825020 ARS Argentine Peso $ 3.791090 BOB Bolivian Boliviano $b 7.570800 BRL Brazilian Real R$ 1.766500 CAD Canadian Dollar $ 1.037570 CLP Chilean Peso $ …

sql判斷語句

方法一&#xff1a; <if test"null ! orderType and 0 orderType"> order by amountTimes desc </if><if test"null ! orderType and 1 orderType">order by amountTimes asc </if><if test"null ! orderType and 2 …

Thinkphp 整合tcpdf

網上查了些關于tcpdf 使用教程&#xff0c;整合到TP的話&#xff0c;會有些小問題&#xff0c;由于基礎還不是很扎實&#xff0c;花了點時間終于整合OK了。下面介紹步驟&#xff1a; 環境&#xff1a; TP版本&#xff1a;TP3.2.2 tcpdf:tcpdf_6_2_3 1. 將tcpdf_6_2_3.zip解壓在…

多項目開發下的dll文件管理

閱讀目錄&#xff1a;DS01&#xff1a;為什么要對生成的dll文件進行管理&#xff1f;DS02&#xff1a;首先介紹以下兩個DOS命令DS03&#xff1a;第一種實現方法&#xff08;xcopy&#xff09;DS04&#xff1a;第二種實現方法&#xff08;attrib&#xff09;DS05&#xff1a;分享…

關于Java中的隨機數產生

對比兩種寫法&#xff1a; 第一種&#xff1a; public static void main(String args[]){Random random new Random(System.currentTimeMillis());for(int i0; i<20; i){int sindex random.nextInt(2);System.out.println(sindex);}}第二種&#xff1a; public static voi…

視圖

視圖是虛表&#xff0c;是從一個或幾個基本表&#xff08;或視圖&#xff09;中導出的表&#xff0c;在系統的數據字典中僅存放了視圖的定義&#xff0c;不存放視圖對應的數據。視圖是原始數據庫數據的一種變換&#xff0c;是查看表中數據的另外一種方式。可以將視圖看成是一個…

選擇器的并發性

4.3.4 并發性 選擇器對象是線程安全的&#xff0c;但它們包含的鍵集合不是。通過keys( )和selectKeys( )返回的鍵的集合是Selector對象內部的私有的Set對象集合的直接引用。這些集合可能在任意時間被改變。已注冊的鍵的集合是只讀的。如果您試圖修改它&#xff0c;那么您得到的…

mysql 自定義函數之判斷

DELIMITER $$CREATE DEFINERrootlocalhost FUNCTION getMin(a int,b int) RETURNS int(11)BEGINdeclare min int;if(a>b)then set min b;elseif(b>a)then set min a;else set min 0;#end if;end if;RETURN min;END 調用該函數可以如下方式 select getMin(1,2); 返回值…

C/C++的數組名

數組名相當于指向數組第一個元素的地址。數組名不是變量&#xff0c;是地址常量&#xff0c;不能為其賦值。如下&#xff1a;1&#xff09;一維數組中對于數組 a[5] {1, 2, 3, 4, 5};數組名a相當于指向第一個元素a[0]的指針。即 a 與 &a[0] 等價。2&#xff09;二維數組中…