찾다

myeclipse10使用spring框架结合jdbc操作数据库 步骤: 1、引入必要的jar包,使用到了如下的jar包 spring.jar aspectjrt.jar aspectjweaver.jar cglib-nodep-2.1.3.jar common-annotations.jar common-logging.jar common-dbcp.jar common-pool.jar mysql-con

myeclipse10使用spring框架结合jdbc操作数据库

步骤:

1、引入必要的jar包,使用到了如下的jar包

spring.jar

aspectjrt.jar

aspectjweaver.jar

cglib-nodep-2.1.3.jar

common-annotations.jar

common-logging.jar

common-dbcp.jar

common-pool.jar

mysql-connector-java-5.1.13.jar

2、配置命名空间

<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"
       xmlns:<span style="color:#ff0000;">tx="http://www.springframework.org/schema/tx</span>"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
          <span style="color:#ff0000;"> http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd</span>">

3、配置数据源

使用的是从properties读取属性,下面蓝色部分是引入属性文件必要的代码,其中

jdbc.properties是属性文件的名称。
<span style="color:#000066;"><context:property-placeholder location="classpath:jdbc.properties"/></span><!-- 属性占位,提取配置文件中的值 -->   
		<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		    <property name="driverClassName" value="${driverClassName}"/>
		    <property name="url" value="${url}"/>
		    <property name="username" value="${username}"/>
		    <property name="password" value="${password}"/>
		     <!-- 连接池启动时的初始值 -->
			 <property name="initialSize" value="${initialSize}"/>
			 <!-- 连接池的最大值 -->
			 <property name="maxActive" value="${maxActive}"/>
			 <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
			 <property name="maxIdle" value="${maxIdle}"/>
			 <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
			 <property name="minIdle" value="${minIdle}"/>
	    </bean>
下面是主要的文件的源代码:

beans.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"
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
        <context:property-placeholder location="classpath:jdbc.properties"/><!-- 属性占位,提取配置文件中的值 -->   
		<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		    <property name="driverClassName" value="${driverClassName}"/>
		    <property name="url" value="${url}"/>
		    <property name="username" value="${username}"/>
		    <property name="password" value="${password}"/>
		     <!-- 连接池启动时的初始值 -->
			 <property name="initialSize" value="${initialSize}"/>
			 <!-- 连接池的最大值 -->
			 <property name="maxActive" value="${maxActive}"/>
			 <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
			 <property name="maxIdle" value="${maxIdle}"/>
			 <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
			 <property name="minIdle" value="${minIdle}"/>
	    </bean>
	     <!-- 配置事务管理器 -->
	     <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	     	<property name="dataSource" ref="dataSource"></property>
	     </bean>
	     <!-- 采用@Transactional注解方式使用事务 -->
	     <tx:annotation-driven transaction-manager="txManager"/>
	     
	     <bean id="personService" class="com.gdhdcy.service.impl.PersonServiceBean">
	     	<property name="dataSource" ref="dataSource"></property>
	     </bean>
	     
</beans>
jdbc.properties文件
driverClassName=org.gjt.mm.mysql.Driver
url=jdbc\:mysql\://localhost\:3306/person?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=root
initialSize=1
maxActive=500
maxIdle=2
minIdle=1
数据库实现增删查改的java文件
package com.gdhdcy.service.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.gdhdcy.bean.Person;
import com.gdhdcy.service.PersonService;

//声明事务,这样就会自动的打开事务和关闭事务
@Transactional
public class PersonServiceBean implements PersonService {
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void delete(Integer personid) {
		jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
				new int[]{java.sql.Types.INTEGER});
	}

	public Person getPerson(Integer personid) {		
		return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid}, 
				new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());
	}

	@SuppressWarnings("unchecked")
	public List<Person> getPersons() {
		return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());
	}

	public void save(Person person) {
		
		jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},
				new int[]{java.sql.Types.VARCHAR});
		System.out.println("保存成功");
	}

	public void update(Person person) {
		jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},
				new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});
	}
}
下面是完整源代码下载链接

http://pan.baidu.com/s/1ntG6T3z

下载文件直接导入到您的myeclipse,然后建立mysql的数据库(数据库文件也在代码文件夹中)。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
MySQL은 다른 RDBM에 비해 동시성을 어떻게 처리합니까?MySQL은 다른 RDBM에 비해 동시성을 어떻게 처리합니까?Apr 29, 2025 am 12:44 AM

mysqlhandlesconcurrencyusingamixofrow-reveltable-levellocking, 주로 throughinnodb'srow-levellocking.comparedtootherrdbms, mysql 's trofficefice formanyusecasesbutmayfacechallengeswithdeadlocksandlacksadvancturespostpostgresql'sserializa

MySQL은 다른 관계형 데이터베이스에 비해 트랜잭션을 어떻게 처리합니까?MySQL은 다른 관계형 데이터베이스에 비해 트랜잭션을 어떻게 처리합니까?Apr 29, 2025 am 12:37 AM

mysqlhandlestransactionseffectialthicatied theinnodbengine, support-propertiessimilartopostgresqlandoracle.1) mysqlusesepeatablereadasthedefaultisolationlevel, itpoptormizestperformance와 함께

MySQL에서 사용 가능한 데이터 유형은 무엇입니까?MySQL에서 사용 가능한 데이터 유형은 무엇입니까?Apr 29, 2025 am 12:28 AM

MySQL 데이터 유형은 숫자, 날짜 및 시간, 문자열, 이진 및 공간 유형으로 나뉩니다. 올바른 유형을 선택하면 데이터베이스 성능 및 데이터 스토리지를 최적화 할 수 있습니다.

MySQL에서 효율적인 SQL 쿼리를 작성하기위한 모범 사례는 무엇입니까?MySQL에서 효율적인 SQL 쿼리를 작성하기위한 모범 사례는 무엇입니까?Apr 29, 2025 am 12:24 AM

모범 사례에는 다음이 포함됩니다. 1) 데이터 구조 및 MySQL 처리 방법 이해, 2) 적절한 인덱싱, 3) 선택을 피하십시오*, 4) 적절한 결합 유형 사용, 5)주의와 함께 하위 쿼리 사용, 6) 설명과 함께 쿼리 분석, 7) 서버 리소스에 대한 쿼리의 영향을 고려하십시오. 8) 데이터베이스를 정기적으로 유지하십시오. 이러한 관행은 MySQL 쿼리를 빠르게 만들뿐만 아니라 유지 보수, 확장 성 및 자원 효율성을 만들 수 있습니다.

MySQL은 PostgreSQL과 어떻게 다릅니 까?MySQL은 PostgreSQL과 어떻게 다릅니 까?Apr 29, 2025 am 12:23 AM

mysqlisbetterforspeedandsimplicity, 적절한 위장; postgresqlexcelsincmoMplexDatascenarioswithrobustFeat.MySqlisIdeAlforQuickProjectSandread-Heavytasks, whilepostgresqlisprefferredforapticationstrictaintetaintegritytetegritytetetaintetaintetaintegritytetaintegritytetaintegritytetainte

MySQL은 데이터 복제를 어떻게 처리합니까?MySQL은 데이터 복제를 어떻게 처리합니까?Apr 28, 2025 am 12:25 AM

MySQL은 비동기식, 반 동시성 및 그룹 복제의 세 가지 모드를 통해 데이터 복제를 처리합니다. 1) 비동기 복제 성능은 높지만 데이터가 손실 될 수 있습니다. 2) 반 동기화 복제는 데이터 보안을 향상 시키지만 대기 시간을 증가시킵니다. 3) 그룹 복제는 고 가용성 요구 사항에 적합한 다중 마스터 복제 및 장애 조치를 지원합니다.

설명 명세서를 사용하여 쿼리 성능을 분석 할 수있는 방법은 무엇입니까?설명 명세서를 사용하여 쿼리 성능을 분석 할 수있는 방법은 무엇입니까?Apr 28, 2025 am 12:24 AM

설명 설명은 SQL 쿼리 성능을 분석하고 개선하는 데 사용될 수 있습니다. 1. 쿼리 계획을 보려면 설명 명세서를 실행하십시오. 2. 출력 결과를 분석하고 액세스 유형, 인덱스 사용량 및 조인 순서에주의를 기울이십시오. 3. 분석 결과를 기반으로 인덱스 생성 또는 조정, 조인 작업을 최적화하며 전체 테이블 스캔을 피하여 쿼리 효율성을 향상시킵니다.

MySQL 데이터베이스를 어떻게 백업하고 복원합니까?MySQL 데이터베이스를 어떻게 백업하고 복원합니까?Apr 28, 2025 am 12:23 AM

논리 백업에 mysqldump를 사용하고 핫 백업을 위해 mysqlenterprisebackup을 사용하는 것은 mySQL 데이터베이스를 백업하는 효과적인 방법입니다. 1. MySQLDUMP를 사용하여 데이터베이스를 백업합니다 : MySQLDUMP-UROOT-PMYDATABASE> MYDATABASE_BACKUP.SQL. 2. Hot Backup : MySQLBackup- 사용자 = root-password = password-- backup-dir =/path/to/backupbackup에 mysqlenterprisebackup을 사용하십시오. 회복 할 때 해당 수명을 사용하십시오

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경