스프링 다오의 JDBC
Spring이 제공하는 DAO (Data Access Object) 지원의 주요 목적은 JDBC, Hibernate 또는 JDO와 같은 표준 방식으로 다양한 데이터 액세스 기술을 사용하는 것입니다. 이를 통해 이러한 지속성 기술 사이를 쉽게 전환 할 수있을뿐만 아니라 인코딩시 다양한 기술에서 특정 예외를 처리 할 필요가 없습니다.
Spring은 일관된 방식으로 JDBC, JDO 및 최대 절전 모드와 같은 다양한 데이터 액세스 기술의 사용을 용이하게하기 위해 확장 할 수있는 추상 DAO 클래스를 제공합니다. 이 추상 클래스는 현재 사용중인 데이터 액세스 기술과 관련된 데이터 소스 및 기타 구성 정보를 얻을 수있는 몇 가지 방법을 제공합니다.
DAO 지원 클래스 :
JDBCDAOSUPPORT- JDBC 데이터 액세스 오브젝트의 기본 클래스. 데이터 소스가 필요하며 서브 클래스에는 jdbctemplate가 제공됩니다.
Hibernatedaosupport- 최대 절전 모드 데이터 액세스 개체의 기본 클래스. SessionFactory가 필요하며 서브 클래스에 대한 최대 절단판이 제공됩니다. 또한 HibernateTemplate를 제공하여 직접 초기화하도록 선택할 수 있으므로 후자의 설정을 SessionFactory, Flush Mode, Exception Translator 등과 같이 재사용 할 수 있습니다.
JDODAOSUPPORT- JDO 데이터 액세스 오브젝트의 기본 클래스. 서브 클래스에 대한 jdotemplate을 설정하고 제공하려면 PeristencemanAgerFactory가 필요합니다.
JPADAOSUPPORT- JPA 데이터 액세스 오브젝트의 기본 클래스. EntityManagerFactory가 필요하며 서브 클래스에는 JPATEMPLATE가 제공됩니다.
이 섹션에서는 주로 JDBCDAOSUPPORT에 대한 Spring의 지원에 대해 설명합니다.
예는 다음과 같습니다.
드롭 테이블 사용자가있는 경우; /*========================================================================================= /*================================================================* / 테이블 사용자 생성
공개 클래스 사용자 {개인 정수 ID; 개인 문자열 이름; 개인 정수 시대; 공개 정수 getId () {return id; } public void setId (정수 ID) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public integer getage () {return age; } public void setage (정수 시대) {this.age = age; }} /** * Intellij Idea에 의해 만들어졌습니다. <br> * <b> 사용자 </b> : leizhimin <br> * <b> 날짜 </b> : 2008-4-22 15:34:36 <br> * <b> note </b> : dao 인터페이스 */public interface iuserdao {public void Insert (사용자 사용자); 공개 사용자 찾기 (정수 ID); } import javax.sql.datasource; java.sql.connection 가져 오기; java.sql.sqlexception 가져 오기; /*** Intellij Idea에 의해 생성되었습니다. <br>* <b> 노 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; }}/** * Intellij Idea에 의해 생성. <br> * <b> 사용자 </b> : leizhimin <br> * <b> date </b> : 2008-4-22 15:36:04 <br> * <b> 노트 </b> : dao 구현 */public class userdao 확장 iuserdao {public jdbcteplepte. getJdbctemplate () {return new jdbctemplate (getDatasource ()); } public void insert (user user) {string name = user.getName (); int age = user.getage (). intvalue (); // jdbctemplate.update ( "user (name, age)"// + "values ( '" + name + "," + age + "); 문자열 sql = "사용자에 삽입 (이름, 연령) 값 (?,?)"; getJdbctemplate (). update (sql, new Object [] {name, age}); } public user find (정수 ID) {list rows = getJdbctemplate (). QueryForList ( "select * where id =" + id.intValue ()); iterator it = rows.iterator (); if (it.hasnext ()) {map usermap = (map) it.next (); 정수 i = new Integer (usermap.get ( "id"). tostring ()); 문자열 이름 = usermap.get ( "name"). toString (); 정수 Age = New Integer (usermap.get ( "age"). tostring ()); 사용자 user = 새 사용자 (); user.setid (i); user.setName (이름); user.setage (나이); 리턴 사용자; } return null; }}<? xml version = "1.0"encoding = "utf-8"?> <! doctype beans public "-// spring/dtd bean/en" "http://www.springframework.org/dtd/spring-beans.dtd"> <bean id = "dataSource"singleton = "property came"> <value> com.mysql.jdbc.driver </value> </value> </property> <속성 이름 = "url"> <value> jdbc : mysql : // localhost : 3306/springdb </value> </property> <속성 이름 = "username"> <value> root </value> </property name = "property> </balue> <value> </balk"> <bean id = "basedao"acpract = "true"> <property name = "dataSource"> <ref bean = "dataSource"/> </property> </bean> <bean id = "userdao"parent = "basedao"> </bean> </beans>
import org.springframework.context.applicationcontext; import org.springframework.context.support.filesystemxmlapplicationContext; /** * Intellij Idea에 의해 생성. <br> * <b> user </b> : leizhimin <br> * <b> date </b> : 2008-4-22 15:59:18 <br> * <b> note </b> : 클라이언트, 클라이언트 */public static void main (string [] args) {newcontect Conte) filesystemxmlapplicationcontext ( "d : //_spring//src//com/lavasoft//springnote//ch05_jdbc03_temp//bean-jdbc-temp.xml"); 사용자 user = 새 사용자 (); user.setName ( "hahhah"); user.setage (새 정수 (22)); iuserdao userdao = (iuserdao) context.getBean ( "userDao"); userdao.insert (사용자); user = userdao.find (new Integer (1)); System.out.println ( "이름 :" + user.getName ()); }}
실행 결과 :
log4j : logger (org.springframework.core.collectionfactory)에 대한 부록을 찾을 수 없습니다. LOG4J : 경고로 LOG4J 시스템을 올바르게 초기화하십시오. 이름 : JDBCTEMPLATE 프로세스 EXIT 코드 0으로 완료되었습니다
스프링 다오의 최대 절전 모드
Hibernatedaosupport- 최대 절전 모드 데이터 액세스 개체의 기본 클래스. SessionFactory가 필요하며 서브 클래스에 대한 최대 절단판이 제공됩니다. 또한 HibernateTemplate를 제공하여 직접 초기화하도록 선택할 수 있으므로 후자의 설정을 SessionFactory, Flush Mode, Exception Translator 등과 같이 재사용 할 수 있습니다.
이 섹션에서는 주로 HibernateTemplate에 대한 Spring의 지원에 대해 설명합니다.
예는 다음과 같습니다.
드롭 테이블 사용자가있는 경우; /*========================================================================================= /*================================================================* / 테이블 사용자 생성
/*** Intellij Idea에 의해 생성됩니다. 개인 문자열 이름; 개인 정수 시대; 공개 정수 getId () {return id; } public void setId (정수 ID) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public integer getage () {return age; } public void setage (정수 시대) {this.age = age; }}<? xml version = "1.0"encoding = "utf-8"?> <! doctype hibernate 맵핑 공개 "-// hibernate/hibernate 매핑 dtd 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> 이름 = "com.lavasoft.springnote.ch06_hbm_02detx.user"table = "user"> <id name = "id"column = "id"> <generator/> </id> <property name = "이름"열 = "name"/<property name = "age"column = "age"/> </hibernate-mapping>
/** * Intellij Idea에 의해 생성. <br> * <b> 사용자 </b> : leizhimin <br> * <b> date </b> : 2008-4-23 15:37:43 <br> * <b> note </b> : dao 인터페이스 */public interface iuserdao {public void Insert (사용자 사용자); 공개 사용자 찾기 (정수 ID); } import org.hibernate.sessionFactory; org.springframework.orm.hibernate3.hibernateTemplate; /** * Intellij Idea에 의해 만들어졌습니다. <br> * <b> 사용자 </b> : leizhimin <br> * <b> 날짜 </b> : 2008-4-23 15:15:55 <br> * <b> note </b> : public class userdao는 iuserdao {private hibernatetemplate platple; public void setsessionSectionFactory (SessionFactory SessionFactory) {this.HiberNateTemplate = New HiberNateTemplate (SessionFactory); } public void insert (사용자 사용자) {hibernateTemplate.save (user); System.out.println ( "저장된 사용자 개체의 ID :"+user.getId ()); } 공개 사용자 찾기 (정수 ID) {user user = (사용자) hibernateTemplate.get (user.class, id); 리턴 사용자; }}<? xml version = "1.0"alcoding = "utf-8"?> <! doctype beans public "-// spring/dtd bean/en" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> "bean id ="dataSource "> <value> com.mysql.jdbc.driver </value> </value> </property> <속성 이름 = "url"> <value> jdbc : mysql : // localhost : 3306/springdb </value> </property> <속성 이름 = "username"> <value> root </value> </property name = "property> </balue> <value> </balk"> <bean id = "sessionFactory"Destroy-Method = "Close"> <속성 이름 = "DataSource"> <Ref Bean = "dataSource"/</property> <속성 이름 = "mappingResources"> <list> <list> com/lavasoft/springnote/ch06_HBM_02PROTX/USER.HBM.XML </value> </value> </value> </value> </value> 이름 = "HibernateProperties"> <props> <prop key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> </props> </bean> <bean id = "userdao"> <property name = "sessionfactory"> ref bean = "sessionfactory"/</bean ".
import org.springframework.context.applicationcontext; import org.springframework.context.support.filesystemxmlapplicationContext; /*** Intellij Idea에 의해 생성. <br>* <b> note </b> : 테스트 클래스, 클라이언트*/public class springhibernatedemo {public static void main (string [] args) {ApplicationContext Context = New filesystemxmlapplicationcontext ( "d : //_spring//src/com/lavasoft//springnote//ch06_hbm_02protx//bean-hbm_tx.xml"); // dao 객체 생성 iuserdao userdao = (iuserdao) context.getBean ( "userDao"); 사용자 user = 새 사용자 (); user.setName ( "CaterPillar"); user.setage (새 정수 (30)); userdao.insert (사용자); user = userdao.find (new Integer (1)); System.out.println ( "이름 :" + user.getName ()); }}
실행 결과 :
log4j : logger (org.springframework.core.collectionfactory)에 대한 부록을 찾을 수 없습니다. log4j : 경고로 log4J 시스템을 올바르게 초기화하십시오. 저장된 사용자 개체의 ID : 18 이름 : JDBCTEMPLATE 프로세스 종료 코드로 완료되었습니다 0