이 기사는 Spring Development_JDBC MySQL 데이터베이스의 Spring Development_JDBC 작업을 다음과 같이 소개합니다.
프로젝트 구조 :
데이터베이스 테이블 :
/spring_1100_spring+jdbc/src/com/b510/bean/person.java
package com.b510.bean;/** * 정상적인 Javabean 클래스 사람 * * @author hongten * */public class person {/** * id number */private int id; / ** * 이름 */ 개인 문자열 이름; / ** * AGE */ Private Int Age; / ** * 성별 */ 개인 문자열 섹스; 공개 사람 (int id, 문자열 이름, int age, string sex) {this.id = id; this.name = 이름; this.age = age; this.sex = 섹스; } public person () {} public int getId () {return id; } public void setid (int id) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public int getage () {반환 연령; } public void 설정 (int Age) {this.age = age; } public String getSex () {return sex; } public void setsex (String sex) {this.sex = sex; }} /spring_1100_spring+jdbc/src/com/b510/service/personservice.java
package com.b510.service; import java.util.list; import com.b510.bean.person; public interface personservice { / ** * 저장 사람 * * @param person * / public actract void save (사람); / ** * 업데이트 사람 * * @Param Person */ Public Abstract void update (개인); / ** * Get Person * * @param id * @return */ public Abstract Person GetPerson (정수 ID); / ** * 모든 사람을 얻습니다 * * @return */ public acpract list <person> getperson (); / ** * 지정된 id * * @param id */ public Abstract void delete (정수 ID)로 사람을 삭제합니다.} /spring_1100_spring+jdbc/src/com/b510/service/impl/personservicebean.java
package com.b510.service.impl;import java.util.List;import javax.sql.DataSource;import org.springframework.jdbc.core.JdbcTemplate;import com.b510.bean.Person;import com.b510.service.PersonService;/** * Business bean * * @author Hongten * */public class personservicebean은 personservice { / ** * data source * / private dataSource dataSource를 구현합니다. / *** JDBC 작동 보조 클래스 Spring*/ private jdbctemplate Jdbctemplate; // 데이터 소스 설정 public void setDatasource (DataSource DataSource) {this.jdbctemplate = new JDBCTemplate (DataSource); } public void save (person) {jdbctemplate.update ( "사람 (이름, 연령, 성) 값 (?,?,?)", new Object [] {] {person.getName (), person.getSex ()}, new int [] {java.sql.types.varch, java.sql. java.sql.types.varchar}); } public void update (person) {jdbctemplate.update ( "업데이트 사람 세트 이름 =?, age =?, sex =? where id =?", new Object [] {person.getName (), person.getage (), person.getId (), new int [] {java.sql.types. java.sql.types.integer, java.sql.types.varchar, java.sql.types.integer}); } 공개 사람 getperson (정수 ID) {person person = (person) jdbctemplate.queryforObject ( "select *에서 id =? 귀환 담당자; } @SuppressWarnings ( "확인되지 않은") 공개 목록 <person> getperson () {list <person> list = jdbctemplate.query ( "선택 *에서 person", new PersonRowMapper ()); 반환 목록; } public void delete (정수 ID) {jdbctemplate.update ( "id =??", new Object [] {id}, new int [] {java.sql.types.integer}); }} /spring_1100_spring+jdbc/src/com/b510/service/impl/personrowmapper.java
package com.b510.service.impl;import java.sql.ResultSet;import java.sql.SQLException;import org.springframework.jdbc.core.RowMapper;import com.b510.bean.Person;public class PersonRowMapper implements RowMapper { @Override public Object mapRow(ResultSet set, int index) throws SQLException { Person person = 새 사람 (set.getInt ( "id"), set.getString ( "name"), set .getInt ( "age"), set.getString ( "sex")); 귀환 담당자; }} /spring_1100_spring+jdbc/src/com/b510/test/springjdbctest.java
패키지 com.b510.test; import java.util.list; import org.springframework.context.applicationcontext; import org.springframework.context.support.classPathLapplicationContext; import com.b510.bean.person; import com.b510.service.perservice.perservice.perservice.perservice.perservice. static void main (String [] args) {ApplicationContext Act = New ClassPathXmlApplicationContext ( "bean.xml"); personservice personservice = (personservice) act .getbean ( "personservice"); 사람 = 새로운 사람 (); person.setname ( "Su dongpo"); person.setage (21); person.setsex ( "male"); // 레코드 저장 personservice.save (person); list <person> person1 = personservice.getperson (); System.out.println ( "++++++++ 모든 사람을 얻습니다"); for (person2 : person1) {system.out.println (person2.getId () + "" + " + person2.getName () +" " + person2.getage () +" + " + person2.getSex ()); } person updateperson = new Person (); UpdatePerson.setName ( "Divide"); UpdatePerson.Setage (20); updateperson.setsex ( "male"); UpdatePerson.SetId (5); // record personservice.update (updateperson)를 업데이트합니다. System.out.println ( "*********************"); // 레코드를받는 사람을 얻습니다. oneperson = personservice.getPerson (2); system.out.println (oneperson.getId () + "" + onePerson.getName () + "" + onePerson.getage () + "" + oneperson.getSex ()); // 레코드 삭제 personservice.delete (1); }} /spring_1100_spring+jdbc/src/bean.xml
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : context = "http://www.springframework.org/schema/context"xmlns : aop = "http://www.springframework.org/schema/aop"xmlns : tx = "http://www.spramwork.org/schema/schema/schema/schema. xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.xsd http://www.springframework.org/schema/contet http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/sprring--5-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.spramework.org/schema/tx-tx-2.5.xsd "! id = "dataSource"destry-method = "close"> <property name = "driverclassName"value = "org.gjt.mm.mysql.driver" /> <property name = "url"value = "jdbc : // localhost : 3307 /spring? useunicode = true & characterEncoding = utf-8" /> < "" ""userem ". <속성 이름 = "비밀번호"value = "root" /> <!-연결 풀이 시작될 때의 초기 값-> <속성 이름 = "이니셜 크기"value = "1" /> <!-연결 풀의 최대 값-> <속성 "value ="300 " /> <!-최대 유휴 값. 피크 시간 후, 연결 풀은 사용하지 않은 연결 중 일부를 천천히 해제하고 maxidle-> <속성 이름 = "maxidle"value = "2" /> <!-최소 유휴 값까지 줄일 수 있습니다. 유휴 연결 수가 임계 값보다 작을 때, 홍수 피크가 올 때 적용 할 시간을 피하기 위해 연결 풀이 일부 연결에 미리 적용됩니다.> <속성 이름 = "minidle"value = "1" /> < /bean> <!-주석을 사용하여 트랜잭션을 구성하십시오. 데이터 소스의 트랜잭션 관리자의 경우 DataSourcetRansactionManager 클래스의 속성 데이터 소스에 정의 된 데이터 소스를 주입합니다 .-> <bean id = "txmanager"> <property name = "dataSource"ref = "dataSource" /> < /bean> <!-NamesPace를 소개하십시오. 1.xmlns : tx = "http://www.springframework.org/schema/tx 2.http : //www.springframework.org/schema/tx http://www.spramework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 트랜잭션 관리자를 사용하여 트랜잭션 관리자를 사용하여-> <tx : 주석-구조 트랜잭션-매너 = "txmanager"/> <!-sulepigure service bean-> <be id = "-persongerevice" "-persongervice" DataSource-> <property name = "dataSource"ref = "dataSource"> </property> </bean> </beans>
실행 결과;
2012-3-9 23:30:57 org.springframework.context.support.abstractApplicationContext PrepareRefresh 정보 : org.sprameframework.context.support.classPathxmlApplicationContext@1A05308 : 디스플레이 이름 [org.springframework.context.support.classpathxmlapplicationcontext@1a05308]; 시작 날짜 [Fri 3 월 23:30:57 CST 2012]; 컨텍스트의 루트 Hierarchy2012-3-9 23:30:57 org.springframework.beans.beans.beans.factory.xml.xmlbeandefinitionreader loadbeandefinitions 정보 : 클래스 경로 자원에서 XML Bean 정의로드 [Bean.xml] 2012-3-9 23:30:58 org.springframework.context.support.abstractapplicationcontext gacefreshbeanfactory 정보 : 응용 프로그램 컨텍스트를위한 Bean Factory [org.springframework.context.support.classPathMlapplicationContext@1a05308] : org.springframework.beans.bean.support.defaultlistablebeanfactory@2bb5142012-3-9 23:30:58 org.springframework.beans.beans.support.defaultlistablebeanCactory preintantesingletons : 싱글 턴스 싱글 톤 org.springframework.bean.bean.support.defaultlistablebeanfactory@2bb514 : 콩 정의 [DataSource, Txmanager, Org.springframework.aop.config.internalautoproxycreator, org.springframework.transaction.annotation.annotationTransactionAttributesour CE#0, org.springframework.transaction.interceptor.TransactionInterceptor#0, org.springframework.transaction.config.internaltransactionAdvisor, personservice]; 공장 계층의 근본 +++++++++++ 모든 Person2 Tomcat 12 여성 3 hongten 21 남성 4 Liufang 21 여성 5 가지 나누기 20 남성 6 Jone 20 여성 7 Su Dongpo 21 Male *********************** 2 Tomcat 12 Female
물론 구성 파일을 사용하여 데이터 소스 정보를 저장할 수 있습니다.
/spring_1100_spring+jdbc/src/jdbc.properties
DriverClassName = org.gjt.mm.mysql.driverUrl = jdbc/: mysql/: // localhost/: 3307/spring? useUnicode/= true & char
수정에 해당합니다.
/spring_1100_spring+jdbc/src/bean.xml
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : context = "http://www.springframework.org/schema/context"xmlns : aop = "http://www.springframework.org/schema/aop"xmlns : tx = "http://www.spramwork.org/schema/schema/schema/schema. xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.xsd http://www.springframework.org/schema/contet http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/sprring--5-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.spramework.org/schema/tx/spring-2.5.xsd "! 구성 파일-> <context : property-placeholder location = "classpath : jdbc.properties" /> <!-구성 데이터 소스-> <bean id = "dataSource"downside-method = "close"> <속성 이름 = "driverclassName"value = "$ {driverClassName}"/> 이름 = "username"value = "$ {username}" /> <속성 이름 = "password"value = "$ {password}" /> <!-연결 풀이 시작될 때의 초기 값-> <속성 이름 = "initialsize"value = "$ {initialsize}" /> <!-<속성 이름 = "maxactive" "$ {maxActive}",} 값. 피크 시간 후 연결 풀은 사용하지 않은 연결의 일부를 천천히 해제하여 maxidle-> <속성 이름 = "maxidle"value = "$ {maxidle}" /> <!-최소 유휴 값까지 줄일 수 있습니다. 유휴 연결 수가 임계 값보다 작을 때, 홍수 피크가 올 때 적용 할 시간을 피하기 위해 연결 풀이 일부 연결에 미리 적용됩니다 .-> <속성 이름 = "minidle"value = "$ {minidle}" /> < /bean> <!-주석을 사용하여 트랜잭션을 구성하십시오. 데이터 소스의 트랜잭션 관리자의 경우 DataSourcetRansactionManager 클래스의 속성 데이터 소스에 정의 된 데이터 소스를 주입합니다 .-> <bean id = "txmanager"> <property name = "dataSource"ref = "dataSource" /> < /bean> <!-NamesPace를 소개하십시오. 1.xmlns : tx = "http://www.springframework.org/schema/tx 2.http : //www.springframework.org/schema/tx http://www.spramework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 트랜잭션 관리자를 사용하여 트랜잭션 관리자를 사용하여-> <tx : 주석-구조 트랜잭션-매너 = "txmanager"/> <!-sulepigure service bean-> <be id = "-persongerevice" "-persongervice" DataSource-> <property name = "dataSource"ref = "dataSource"> </property> </bean> </beans> 실행 결과는 동일합니다.
2012-3-10 0:23:59 org.springframework.context.support.abstractApplicationContext PrepareReshearn Informath : Romforming org.spramextr.support.classpathxmlapplicationcontext@c1b531 : 디스플레이 이름 [org.springframework.context.support.classpathxmlapplicationcontext@c1b531]; 시작 날짜 [SAT MAR 10 00:23:59 CST 2012]; 컨텍스트의 루트 Hierarchy2012-3-10 0:23:59 org.springframework.beans.beans.factory.xml.xmlbeandefinitionreader loadbeandefinitions 정보 : 클래스 경로 자원에서 XML Bean 정의로드 [Bean.xml] 2012-3-10 0:23:59 org.springframework.context.support.abstractapplicationcontext gacefreshbeanfactory 정보 : 응용 프로그램 컨텍스트를위한 Bean Factory [org.springframework.context.support.classPathxmlapplicationContext@c1b531] : org.springframework.beans.bean.support.defaultlistablebeanfactory@1aa57fb2012-3-10 0:23:59 org.springframework.core.io.support.propertiesloadersupport loadproperties 정보 : Classe Path Resource의로드 PRATHITIES [JDBC.PORETIES]. 0:23:59 org.springframework.bean.beans.support.support.support.defaultlistablebeanfactory preinstantesingletonsingletons instantesingletons 정보 : org.springframework.beans.support.defaultlistablebeanfactory@1aa57fb : 콩 조절 [org.springframework.beans.factory.config.propertyplaceholderconfigurer#0, DataSource, Txmanager, org.sprameframework.aop.config.internalautoproxycreator, org.springframework.transaction.annotati on.annotationTransactionAttributeSource#0, org.springframework.transaction.interceptor.transactionInterceptor#0, org.springframework.transaction.config.internaltransactionAdvisor, personservice]; 공장 계층의 근본 ++++++++++++ get All Person2 Tomcat 12 여성 3 Hongten 21 남성 4 Liufang 21 여성 5 분할 20 남성 6 Jone 20 여성 7 Su Dongpo 21 Male 8 Su Dongpo 21 남성 ************************ 2 Tomcat 12 Female
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.