Springmvc + Spring 3.2.14 + Hibernate 3.6.10 Integration
Note: This document only describes simple framework integration, and the advanced features of each frame are not covered, and newcomers to the framework may need to refer to other materials.
PS: The jar package for this exercise can be downloaded here: Http://pan.baidu.com/s/1sjmgdYX
Development environment:JDK 7u80,Eclipse 4.4,Tomcat 7.0.63,MySQL 5.6
Development uses components: Spring 3.2.14, Hibernate 3.6.10, Common-logging 1.2, Aopalliance.jar,Aspectjweaver.jar, Mysql-connector-java-5.1.35-bin.jar
Create a dynamic Web project Test under Eclipse, note the option to check web. XML when creating, and if unchecked, create Web. XML after the project is created , deploy it to In Tomcat, the project structure should look like this (under Package Explorer, see Personal Habits ):
Copy the following jar packages to the Lib folder, and don't ask why, and wonder why you can delete any of the others and see what's wrong with the startup project.
Configure the spring listener in Web. XML with the following code:
<listener> <listener-class>org.springframework.web.context.contextloaderlistener</ Listener-class></listener>
Create Applicationcontext.xml, the current version of spring defaults to its location under Web-inf, but most developers are accustomed to putting it under SRC, where we put it under src. Then add the bean -related declarations to Applicationcontext.xml, as follows
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd "></beans>
Add the following in Web. XML to customize the location of the spring configuration file:
<context-param> <param-name>contextConfigLocation</param-name> <param-value> Classpath:applicationcontext.xml</param-value></context-param>
New test entity class user, the path is tentatively com.test.entity, add the following code:
Package Com.test.entity;public class User { private String ID; Private String username; private String password; Public String getId () { return ID; } public void SetId (String id) { this.id = ID; } Public String GetUserName () { return username; } public void Setusername (String username) { this.username = username; } Public String GetPassword () { return password; } public void SetPassword (String password) { this.password = password; } }
The following definitions are added in Applicationcontext.xml (which can be removed after the test is completed):
<bean id= "user" class= "com.test.entity.User" > <property name= "username" value= "test"/></bean >
New test class, tentative path com.test.test, add the following code:
Package Com.test.test;import Org.springframework.context.support.filesystemxmlapplicationcontext;import Com.test.entity.user;public class test{ @SuppressWarnings ("resource") public static void Main (string[] args) { Filesystemxmlapplicationcontext ac = new Filesystemxmlapplicationcontext ("Src\\applicationcontext.xml") ; User user = (user) Ac.getbean ("user"); System.out.println (User.getusername ()); } }
Run the test class to see the results, and if the output test indicates that the Spring framework is working properly.
To add the required jar packages for SPRINGMVC: Spring-webmvc-3.2.14.release.jar, add SPRINGMVC Front Controller related configuration in Web. config, springmvc configuration file default servlet configuration name-servlet.xml ( For example, this should be Springmvc-servlet.xml), located under Web-inf, where we merge the spring configuration file with the SPRINGMVC configuration file, so we need to describe the location of the configuration file when configuring Dispatcherservlet , configured as follows:
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> < Param-name>contextconfiglocation</param-name> <param-value>classpath:applicationcontext.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </ servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> < Url-pattern>*.do</url-pattern> </servlet-mapping>
Configure the SPRINGMVC scanner to scan the SPRINGMVC annotations, where the context tag is needed, so you need to add a context document declaration, all the code is as follows:
<?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 " xsi:schemalocation=" Http://www.springframework.org/schema/beans/ http Www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd "> <context:component-scan Base-package= "Com.test"/> <bean id= "user" class= "com.test.entity.User" > <property name= " Username "value=" test "/>
To configure the view resolver, thecontroller layer will return data or view after processing the request, so we need to add the view parser first, otherwise we can't jump back to the foreground page, the code is as follows:
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= " Suffix "value=". jsp "/> </bean>
Create index.jsp with the following code:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Create return.jsp with the following code:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Create Usercontroller, tentatively located in Com.test.controller, to receive the foreground request, with the following code:
Package Com.test.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.requestmapping;import Com.test.entity.user;import Com.test.service.UserService, @Controller @requestmapping ("/user") public class Usercontroller { @Autowired Private UserService UserService; @RequestMapping ("/test") public String test (User User,modelmap model) { System.out.println (user.getusername ()); System.out.println (User.getpassword ()); Model.addattribute (user); return "/return"; } }
After you start the Tomcat test, the results are as follows, stating that the framework has successfully requested:
- Configure Hibernate integration
Add the following jar packages:
Applicationcontest.xml Add Hibernate related configuration,hibernate entity declaration can choose configuration file and annotations two ways, I personally prefer the configuration file mode, as shown in:
<bean id= "DataSource" class= "Org.apache.tomcat.jdbc.pool.DataSource" > <property name= "url" value= " Jdbc:mysql://localhost:3306/test "/> <property name=" Driverclassname "value=" Com.mysql.jdbc.Driver "/ > <property name= "username" value= "root"/> <property name= "password" value= "root" /> </bean> <bean id= "sessionfactory" class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean "> <property name=" DataSource "ref=" DataSource "/> <property name=" Mappinglocations "> <value>classpath*:/com/test/entity/*.cfg.xml</value> </property> <property name= "Hibernateproperties" > <props> <prop key= "Hibernate.show_sql" >true</prop> </props> </property> </bean>
Since Hibernate3 must handle the data access in the transaction, the transaction control needs to be added, the individual tends to use AOP, so the document configuration of TX and AOP needs to be added first, and the following section of the document declaration code is as follows:
<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:tx="/http/ Www.springframework.org/schema/tx " xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP " xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/ Schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx/ http Www.springframework.org/schema/tx/spring-tx-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http:/ /www.springframework.org/schema/aop/spring-aop-3.2.xsd ">
Configure the transaction controller and weave it into the service plane through AOP for transaction control, as follows:
<bean id= "Txmanager" class= "Org.springframework.orm.hibernate3.HibernateTransactionManager" > < Property Name= "Sessionfactory" ref= "sessionfactory"/> </bean> <tx:advice id= "Txadvice" Transaction-manager= "Txmanager" > <tx:attributes > <tx:method name= "*" propagation= "REQUIRED"/ > </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression= "Execution (* com.test.service.*.* (..))" id= "Aoppointcut"/> <aop:advisor advice-ref= "Txadvice" pointcut-ref= "Aoppointcut"/> </aop:config>
- Testing the overall framework
MySQL creates the test_user table to test whether the framework works properly with the database, where we test the save operation in transaction management, with the following table statements:
CREATE TABLE Test_user ( ID varchar (primary) key, username varchar () Not NULL, password varchar (#) Not n ULL);
Create a Hibernate entity mapping file that reads as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">
Create a Userdao, tentatively located under Com.test.dao, for handling database operations with the following code:
Package Com.test.dao;import Org.hibernate.sessionfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.repository;import Com.test.entity.User; @Repositorypublic class Userdao { @Autowired private sessionfactory sessionfactory; Public String Save (user user) { return (String) sessionfactory.getcurrentsession (). Save (user); } }
Create UserService, tentatively located under Com.test.service, to provide the requested service with the following code:
Package Com.test.service;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Com.test.dao.userdao;import Com.test.entity.User; @Servicepublic Class UserService { @Autowired private Userdao Userdao; Public String Save (user user) { return userdao.save (user); } }
Modify the Usercontroller as follows:
Package Com.test.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.requestmapping;import Com.test.entity.user;import Com.test.service.UserService, @Controller @requestmapping ("/user") public class Usercontroller { @Autowired Private UserService UserService; @RequestMapping ("/test") public String test (User User,modelmap model) { userservice.save (user); Model.addattribute (user); return "/return"; } }
The contents of this project should look like the following:
Restart Tomcat after entering the user name and password, click the button to view the database, the normal result is no error in the background and the database has data deposit, as shown in:
Next we test whether the transaction can be rolled back normally in the event of an exception, modify the service code as follows:
Package Com.test.service;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Com.test.dao.userdao;import Com.test.entity.User; @Servicepublic Class UserService { @Autowired private Userdao Userdao; Public String Save (user user) { userdao.save (user); throw new RuntimeException ("Test transaction can be rolled back properly!") "); }}
After restarting Tomcat, the test framework can be rolled back normally, the background will throw a custom exception, and the second data in the database does not appear, the framework is integrated to this end, then the framework-based development work.
PS: You have any questions or different views can leave a message
Category: Java, database-relatedSpringmvc + Spring 3.2.14 + Hibernate 3.6.10