Cet article présente le fonctionnement de Spring Development_JDBC de la base de données MySQL, comme suit:
Structure du projet:
Tableau de base de données:
/spring_1100_spring+jdbc/src/com/b510/bean/person.java
Package com.b510.bean; / ** * Personne de classe JavaBean normale * * @author hongten * * / public class Person {/ ** * numéro d'identification * / int private id; / ** * nom * / nom de chaîne privée; / ** * Âge * / private int Age; / ** * Sexe * / Sexe à chaîne privée; Personne publique (int id, nom de chaîne, int, sexe de chaîne) {this.id = id; this.name = name; this.age = âge; this.sex = sexe; } Public Person () {} public int getID () {return id; } public void setid (int id) {this.id = id; } public String getName () {Nom de retour; } public void setName (string name) {this.name = name; } public int getage () {return âge; } public void Setage (int Age) {this.age = age; } public String getSEX () {return sexe; } public void setSex (String Sex) {this.sex = sexe; }} /spring_1100_spring+jdbc/src/com/b510/service/personservice.java
package com.b510.service; import java.util.list; import com.b510.bean.person; interface publique PersonService {/ ** * SAVE Person * * @param personne * / public abstract void Save (personne personne); / ** * MISE À JOUR Personne * * @param Person * / Public Abstract Void Update (personne personne); / ** * Get Person * * @param id * @ return * / public abstrait personne getperson (INGER ID); / ** * Obtenez tous les personnes * * @ return * / public abstract List <ponse> getPerson (); / ** * Supprimer la personne avec l'ID spécifié * * @param id * / public abstract void Delete (INGER ID);} /spring_1100_spring+jdbc/src/com/b510/service/impl/personservicebean.java
Package com.b510.service.impl; importer java.util.list; import javax.sql.datasource; import org.springframework.jdbc.core.jdbctemplate; import com.b510.bean.person; importer com.b510.service.personservice; / ** * BEAUCTAL BEAN * * @author hongror * * / classe publique * * * * * PersonServiceBean implémente PersonService {/ ** * Source de données * / private dataSource dataSource; / ** * JDBC Operation Classe auxiliaire fournie par Spring * / JDBCTemplate privé JDBCTemplate; // Définissez la source de données public void setDataSource (dataSource dataSource) {this.jdbctemplate = new JDBCTemplate (dataSource); } public void Save (personne personne) {jdbcTemplate.update ("insérer dans la personne (nom, âge, sexe) valeurs (?,?,?)", nouvel objet [] {personne.getName (), personne.getage (), personne.getsex ()}, new int [] {java.inger, tact java.sql.types.varchar}); } public void Update (personne personne) {jdbcTemplate.update ("Update Person set name =?, Âge =?, Sex =? Where id =?", New Object [] {Person.getName (), Person.getage (), personne.getSex (), Person.getid ()}, new int [] {java.sql.types.varhar. java.sql.types.integer, java.sql.types.varchar, java.sql.types.integer}); } Public Person GetPerson (INTER ID) {Person Person = (Person) JDBCTEmplate.QueryForObject ("SELECT * FROM Person Where Id =?", Nouvel Objet [] {ID}, nouveau int [] {java.sql.types.Integer}, new PersonRowMapper ()); personne de retour; } @SuppressWarnings ("Unchecked") public list <onon> getPerson () {list <ponv> list = jdbCTemplate.Query ("select * from Person", new PersonRowMapper ()); Liste de retour; } public void Delete (Integer id) {jdbCTemplate.update ("Delete de la personne où id =?", Nouvel objet [] {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. Person = new Person (set.getInt ("id"), set.getString ("name"), set .getInt ("Age"), set.getString ("sexe")); personne de retour; }} /spring_1100_spring+jdbc/src/com/b510/test/springjdbcTest.java
package com.b510.test; import java.util.list; import org.springframework.context.applicationContext; import org.springframework.context.support.personclasspathxmlapplicationcontext; import com.b510.bean.person; Importer com.b510.service STATIC main (String [] args) {applicationContext act = new ClassPathXmlApplicationContext ("bean.xml"); PersonService PersonService = (PersonService) ACT .GetBean ("PersonService"); Personne personne = new personne (); personne.setName ("Su Dongpo"); Person.Setage (21); personne.setSEX ("mâle"); // Enregistrer un record PersonService.save (personne); List <onon> person1 = PersonService.getSerson (); System.out.println ("+++++++++ Obtenir toutes les personnes"); pour (Person Person2: Person1) {System.out.println (Person2.getId () + "" + Person2.getName () + "" + Person2.getage () + "" + Person2.getSex ()); } Personne UpdateSerson = new Person (); UpdateSerson.SetName ("Divide"); updateSerson.Setage (20); UpdateSerson.SetSEX ("Male"); UpdateSerson.setid (5); // Mette à jour un enregistrement PersonService.update (UpdateSerson); System.out.println ("********************"); // Obtenez une personne record OneSerson = PersonService.getSerson (2); System.out.println (oneSerson.getId () + "" + oneSerson.getName () + "" + oneSerson.getage () + "" + oneSerson.getSex ()); // Supprimer un record PersonService.Delete (1); }} /spring_1100_spring+jdbc/src/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" xmlns: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframeworkwork.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-20 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 "> <! <bean id = "dataSource" destrement-méthod = "close"> <propriété name = "driverclassname" value = "org.gjt.mm.mysql.driver" /> <propriété name = "url" value = "jdbc: mysql: // localhost: 3307 / printemps? useunicode = true & caractérisation = utf-8" /> /> <propriété name = "mot de passe" value = "root" /> <! - Valeur initiale lorsque le pool de connexion est démarré -> <propriété name = "initialSize" value = "1" /> <! - Valeur maximale du pool de connexion -> <propriété name = "maxactive" value = "300" /> <! - MAXIMUM INDLEAUX INDIGE. Après un temps de pointe, le pool de connexions peut lentement libérer certaines des connexions inutilisées et les réduire jusqu'à maxidle -> <propriété name = "maxidle" value = "2" /> <! - Valeur inactive minimale. Lorsque le nombre de connexions inactives est inférieur au seuil, le pool de connexions pré-appliquera pour certaines connexions afin d'éviter le temps de s'appliquer lorsque le pic d'inondation est venu -> <propriété name = "minidle" value = "1" /> </ank> <! - Utilisez l'annotation pour configurer les transactions. Pour le gestionnaire de transactions de la source de données, injectez la source de données que nous avons définie dans la propriété DataSource de la classe DataSourceTransactionManager -> <bean id = "txManager"> <propriété name = "dataSource" ref = "dataSource" /> </-bean> <! - introduire un espace de noms: 1.xmlns: tx = "http://www.springframework.org/schema/tx 2.http: //www.springframework.org/schema/tx http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd Utilisez l'annotation @transaction pour utiliser le gestionnaire de transactions -> <tx: Configurer le service de transaction-manager = <e Bean Id = "PersonSenser" dataSource -> <propriété name = "dataSource" ref = "dataSource"> </ propriété> </bEAN> </bans>
Résultats en cours d'exécution;
2012-3-9 23:30:57 org.springframework.context.support.abstractApplicationContext preparerefresh Informations: rafraîchissant org.springframework.context.support.classpathxmlapplicationcontext@1a05308: nom d'affichage. [org.springframework.context.support.classpathxmlapplicationcontext@1a05308]; Date de démarrage [ven 09 23:30:57 CST 2012]; Root of Context Hiérarchy2012-3-9 23:30:57 org.springframework.beans.factory.xml.xmlbeandefinitionReader LoadBeanDefinitions Informations: Chargement des définitions de bean XML à partir de la ressource de chemin de classe [Bean.xml] 2012-3-9 23:30:58 org.springframework.context.support.abstractApplicationContext obtient FreshBeanFactory Informations: bean usine pour le contexte de l'application [org.springframework.context.support.classpathxmlapplicationcontext@1a05308]: org.springframework.beans.factory.support.defaultListableBeanfactory@2bb5142012-3-9 23:30:58 org.springframework.beans.factory.support.defaultListableBeanFactory PreinstantiaSEingletOn org.springframework.beans.factory.support.defaultListablebeanfactory@2bb514: Définition des haricots [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]; Root de la hiérarchie d'usine ++++++++++++ Obtenez tout le personnage2 Tomcat 12 Femme 3 Hongten 21 mâle 4 Liufang 21 Femme 5 Divide 20 mâle 6 Jone 20 Femme 7 Su Dongpo 21 Male ************************ 2 Tomcat 12 Femme
Bien sûr, nous pouvons utiliser des fichiers de configuration pour stocker nos informations de source de données:
/spring_1100_spring+jdbc/src/jdbc.properties
DriverClassName = org.gjt.mm.mysql.driverurl = jdbc /: mysql /: // localhost /: 3307 / printemp? useunicode / = true & worseencoding / = utf-8USERNAME = rootpassword = 1 rohinitialSize = 1Maxactive = 300Maxidle = 2MinIdle = 1
En conséquence pour modifier:
/spring_1100_spring+jdbc/src/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" xmlns: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframeworkwork.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-20 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 "> <! - JDBC.Properties Fichier de configuration -> <Context: propriété-placeholder location = "ClassPath: jdbc.properties" /> <! - Source de données de configuration -> <bean id = "dataSource" destère-méthode = " <propriété name = "username" value = "$ {username}" /> <propriété name = "mot de passe" value = "$ {mot de passe}" /> <! - Valeur initiale lorsque le pool de connexion démarre -> <propriété name = "initialSize" value = "MAXIMACT-MAXACTION}" /> <! - MAXIMAL VALEUR DE LA POOL DE CONNEXION -> <propriété Name = "Maxactive" value = "$” $ {max} " valeur inactive. Après un temps de pointe, le pool de connexions peut lentement libérer la partie des connexions inutilisées, réduisant jusqu'à maxidle -> <propriété name = "maxidle" value = "$ {maxidle}" /> <! - Valeur inactive minimale. Lorsque le nombre de connexions inactives est inférieur au seuil, le pool de connexions pré-appliquera pour certaines connexions afin d'éviter le temps de s'appliquer lorsque le pic de crue viendra -> <propriété name = "minidle" value = "$ {minidle}" /> </ank> <! - Utilisez l'annotation pour configurer les transactions. Pour le gestionnaire de transactions de la source de données, injectez la source de données que nous avons définie dans la propriété DataSource de la classe DataSourceTransactionManager -> <bean id = "txManager"> <propriété name = "dataSource" ref = "dataSource" /> </-bean> <! - introduire un espace de noms: 1.xmlns: tx = "http://www.springframework.org/schema/tx 2.http: //www.springframework.org/schema/tx http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd Utilisez l'annotation @transaction pour utiliser le gestionnaire de transactions -> <tx: Configurer le service de transaction-manager = <e Bean Id = "PersonSenser" dataSource -> <propriété name = "dataSource" ref = "dataSource"> </ propriété> </bEAN> </bans> Les résultats de l'exécution sont les mêmes:
2012-3-10 0:23:59 org.springframework.context.support.abstractApplicationContext preparerefresh Informations: rafraîchissant org.springframework.context.support.classpathxmlapplicationcontext@c1b531: affichage le nom [org.springframework.context.support.classpathxmlapplicationcontext@c1b531]; Date de démarrage [samedi 10 mars 00:23:59 CST 2012]; Root of Context Hiérarchy2012-3-10 0:23:59 org.springframework.beans.factory.xml.xmlbeandefinitionReader LoadBeanDefinitions Informations: Chargement des définitions de bean XML à partir de la ressource de chemin de classe [Bean.xml] 2012-3-10 0:23:59 org.springframework.context.support.abstractApplicationContext obtient FreshBeanFactory Informations: bean usine pour le contexte de l'application [org.springframework.context.support.classpathxmlapplicationcontext@c1b531]: org.springframework.beans.factory.support.defaultListableBeanfactory@1aa57fb2012-3-10 0:23:59 org.springframework.core.io.support.propertiesloadhersupport loadproperties Informations: chargement des propriétés de la ressource de patrie de classe [JDBC.properties] 2012-3 - 3-10 Properties Resource Resource path 0:23:59 org.springframework.beans.factory.support.defaultListableBeanFactory PreinstanciateSingletons Informations: pré-installation de singletons dans org.springframework.beans.factory.support.defaultListableBeanfactory@1aa57fb: Dant fans de définition des foyers de définition des fines de définition. [org.springframework.beans.factory.config.propertyPlaceHolderConfigurer # 0, DataSource, TxManager, org.springframework.aop.config.internalautoproxycreator, org.springframework.transaction.annotati on.annotationTransactionAttributesource # 0, org.springframework.transaction.interceptor.transactionInterceptor # 0, org.springframework.transaction.config.internaltransactionAdvisor, PersonService]; Root de la hiérarchie d'usine ++++++++++++++ Obtenez tout le personnage 2 tomcat 12 femelle 3 hongten 21 mâle 4 liufang 21 femelle 5 divide 20 mâle 6 jone 20 feme
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.