J'ai vu beaucoup d'articles sur l'intégration du printemps et de l'hibernate sur Internet, mais parce que ces articles ont été écrits plus tôt, beaucoup d'entre eux étaient des versions plus anciennes telles que le printemps 3 et Hibernate 4. Je vais donc utiliser la version mise à jour ici pour l'illustrer.
Ajouter les dépendances du projet
Tout d'abord, nous avons besoin d'un projet Web Java, qui est préférable d'utiliser des outils de construction Maven ou Gradle pour faciliter nos dépendances logicielles. J'utilise Gradle Build Tool ici, le script de construction est le suivant. Tant que nous introduisons les deux packages de Spring-WebMVC et de Spring-Oor, d'autres dépendances de printemps seront automatiquement résolues par l'outil de construction. Ensuite, vous devez également introduire des dépendances telles que les sources de données, Hibernate, JSTL, etc. Le script définit une tâche pour générer le fichier POM correspondant pour une utilisation facile par Maven Tools.
Groupe 'yitian.learn'version' 1.0-snapshot'apply plugin: 'Java'Apply Plugin:' war'Apply Plugin: 'Maven'Apply from:' https://raw.github.com/akhikhl/gretty/master/plugInScripts/gretty.plugin'sourceCompatibilité = 1.8Re "http://maven.aliyun.com/nexus/content/groups/public/" } jcenter()}ext {springVersion = '4.3.6.RELEASE' aspectjVerison = '1.8.10'} dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile group: 'org.springframework', Nom: `` Spring-webmvc ', version: Springversion Compile Group:' org.springframework ', Nom:' Spring-Lorm ', Version: Springversion Compile Group:' Org.glassfish.web ', Nom:' JSTL-IMPL ', version:' Lombok '' ', version:' Org.12 '' Name ', nom:' Lombok '', version: '1.12' 'org.hibernate', nom: 'Hibernate-core', version: '5.2.6.Final' Compile Group: 'Mysql', nom: 'MySql-Connector-Java', version: '5.1.40' Compile Group: 'org.apache.commons', Name: 'Commons-dbcp2', version: '2.1.1' Compile Group: 'Org.asppectj:', version: '2.1.1' Compile Group: 'Org.asppectj:', version: '2.1.1' Compile Group: 'Org.asppectj:', version: '2.1.1' Compile Group: 'Org.asppectj:', version: '2.1.1' 'AspectJweaver', version: AspectJVerison} tâche écritewpom {Dolast {pom {} .writeTo ("$ projectdir / pom.xml")}}Configurer web.xml
Ouvrez ensuite le fichier Web-inf / web.xml et ajoutez le contenu suivant.
<? xml version = "1.0" encoding = "utf-8"?> <web-app xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version = "3.1"> <context-param> <paramor-name> ContextConfigConconcot <Am param-Value> /Web-inf/ApplicationContext.xml </ Param-Value> </ Context-Param> <Serplet> <Serplet-Name> Dispatcher </ Servlet-Name> <Servlet-Class> Org.SpringFramework.web.Servlet.Dispatcherservlet </ Servlet-Class> <Lo dans le standard> <async-supported> true </ async-supporté> </ servlet> <servlet-mapping> <servlet-name> Dispatcher </ servlet-name> <url-potern> / </ url-Pattern> </ servlet-mapping> <oudinner> <Couner-Class> org.springframework.web.Context.Context. </dinerder> </k-app>
Configurer le ressort
Il devrait y avoir deux fichiers de configuration Spring /Web-inf/ApplicationContext.xml et /web-inf/dispatcher-servlet.xml. Le premier est un fichier de configuration root, qui est utilisé pour configurer des composants arrière et globaux tels que des bases de données, et le second est un fichier de configuration MVC, qui est utilisé pour configurer MVC et les composants liés au Web.
Ensuite, dans /web-inf/applicationContext.xml, nous configurons les composants qui intègrent Hibernate et Spring. Nous devons configurer la source de données, HiberNaSesSessionFactory, Hibernate Transaction Manager, le point de connexion de transaction, le modèle Hibernate et d'autres haricots, puis utiliser le modèle Hibernate lors de la manipulation des données pour obtenir la fonction de gestion des transactions contrôlée par Spring.
<? 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: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: context = "http://www.springframeworkwork.org/schema" XSI: ScheMalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsddwork. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context: annotation-config /> <! - Data Source -> <bean id =" datasource "Destrement-Method =" close "> <proftwawe Value = "com.mysql.jdbc.driver" /> <propriété name = "url" value = "jdbc: mysql: // localhost: 3306 / test" /> <propriété name = "username" value = "root" /> <propriété = "mot de passe" value = "12345678" /> </ bean> <! name = "dataSource" ref = "dataSource" /> <propriété name = "hibernateproperties"> <props> <prop key = "hibernate.format_sql"> true </ prop> <prop key = "hibernate.show_sql"> true </ prop> <prop> <ple key = "hibernate.hbm2ddl.auto"> créer </prop> </ props> </ propriété> <propriété name = "packAnitoscan" value = "yitian.learn.entity" /> </ bean> <! - Set HiberNate Template -> <Bean Id = "HiberNatetemplate"> <propriété Nom = "SessionFactory" <! - Définir Hibernate Transaction Manager -> <bean id = "TransactionManager"> <propriété name = "SessionFactory" Ref = "SessionFactory" /> </ Bean> <! - Définir HiberNate Transaction Manager -> <Bean Id = "TransactionManager"> <! Gestion des transactions -> <tx: conseil id = "txadvice" transaction-manager = "transactionManager"> <tx: attributs> <tx: méthode name = "find *" readly = "true" /> <tx: méthode name = "*" /> </ tx: attributes> </ tx: conseils> <! id = "userdaopointcut" expression = "EXECUTION (* yitian.learn.dao. *. * (..))" /> <aop: conseiller conseils-ref = "txadvice" Pointcut-ref = "userdaOpointcut" /> </ aop: config> </ beans>
Configurez ensuite les composants de Spring Web MVC. Ajoutez la configuration suivante dans Dispatcher-Servlet.xml. Ici, nous ajoutons JSP View Parser et Type Converter. Si vous n'avez pas besoin d'une conversion de type personnalisé, vous pouvez supprimer le fragment correspondant.
<? 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: mvc = "http://www.springframework.org/schema/mvc" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemalation = "http://www.springframework.org/schea/bans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdwork. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <mvc: View-resolvers> <mvc: jsp prefix =" / web-inf / jsp / "Suffix =". View-Class = "org.springframework.web.servlet.view.jstlview" /> </ mvc: View-Resolvers> <Mvc: Default-Servlet-Handler /> <MVC: Annotation-Drived Conversion-Service = "ConversionService" /> <Context: Component-Scan-Package = "Yitian.learn" /> <Beeby Id = "Conversation" <propriété name = "convertisseurs"> <set> <an bean /> </ set> </ propriété> </bant> </bans>
À ce stade, l'intégration entre Hibernate et Spring a été entièrement configurée. Enfin, j'ai écrit un petit exemple et l'ai mis sur Github. Les étudiants intéressés peuvent jeter un œil.
Résumer
Ce qui précède est toute l'explication détaillée de la configuration d'intégration de Spring Web MVC et Hibernate dans cet article, j'espère que cela sera utile à tout le monde. Les amis intéressés peuvent continuer à se référer à d'autres sujets connexes sur ce site. S'il y a des lacunes, veuillez laisser un message pour le signaler. Merci vos amis pour votre soutien pour ce site!