Spring+springmvc+hibernate Consolidation Examples

Source: Internet
Author: User

In the last blog post, the integration of spring and SPRINGMVC was written, and this one added hibernate.

As in the last time, this time, the jar package is still imported, and this time you will join the JAR package in hibernate as shown in:

At the same time, create two new source folders, one for config, one for test, the configuration files and test cases respectively, and now for SPRING,SPRINGMVC and hibernate configuration.

Create a new spring-hibernate.xml,applicationcontext.xml,springmvc.xml,hibernate.cfg.xml four configuration file and now configure the four profiles.

Spring-hibernate.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE beans Public "-//spring//dtd BEAN 2.0//en" "Http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<!    ENTITY contextinclude SYSTEM "Org/springframework/web/context/web-inf/contextinclude.xml" >]><beans> <bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" ><property name = "Driverclassname" value= "Com.mysql.jdbc.Driver" ></property><property name= "url" value= "jdbc:mysql:// Localhost:3306/contacts "></property><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><property name= "hibernateproperties" ><props><prop key= "Hibernate.dialect" >org.hibernate.dialect.mysqldialect</prop><prop key= "Show_sql" >true</proP><prop key= "Hibernate.show_sql" >true</prop> <prop key= "Hiberante.format_sql" >true< /prop></props></property> <property name= "Configlocations" ><list><value> classpath:hibernate.cfg.xml</value></list></property><!--Annotations Scanned Package--<!--<property Name= "Annotatedclasses" > <list> <value></value> </list> </proper ty>--></bean><bean id= "TransactionManager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager "><property name=" sessionfactory "ref=" Sessionfactory "></property></bean><bean id=" Transactionbese "class=" Org.springframework.transaction.interceptor.TransactionProxyFactoryBean "abstract=" true "lazy-init=" true "> <property name= "TransactionManager" ref= "TransactionManager" ></property><property name= " Transactionattributes "><props><prop key=" save* ">Propagation_required,-exception</prop><prop key= "update*" >propagation_required,-exception</prop ><prop key= "delete*" >propagation_required,-exception</prop></props></property></ Bean><bean id= "Hibernatetemplate" class= "Org.springframework.orm.hibernate3.HibernateTemplate" >< Property Name= "Sessionfactory" ><ref bean= "Sessionfactory" ></ref></property></bean> </beans>

Applicationcontext.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE beans Public "-//spring//dtd BEAN 2.0//en" "Http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<! ENTITY contextinclude SYSTEM "Org/springframework/web/context/web-inf/contextinclude.xml" >]><beans> <import resource= "Spring-hibernate.xml" ></import><bean id= "Userdao" class= " Cn.com.dao.impl.UserDaoImpl "><property name=" hibernatetemplate "ref=" Hibernatetemplate "></property ></bean><bean id= "UserService" class= "Cn.com.service.impl.UserServiceImpl" ><property name= " Userdao "ref=" Userdao "></property></bean></beans>
Springmvc.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:mvc= "Http://www.springframework.org/schema/mvc" 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-3.0.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd Http://www.springframework.org/schema/context http ://www.springframework.org/schema/context/spring-context-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http ://www.springframework.org/schema/aop/spring-aop-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/http Www.springframework.org/schema/tx/spring-tx-3.0.xsd "><!--mvc annotation Driver--><mvc:annotation-driven/> <!--Once there is a scanMvc:annotation-driven is not required, the scanner already has the annotation-driven function--><context:component-scan base-package= "Cn.com.controller"/ ><!--prefix + viewName + suffix--><beanclass= " Org.springframework.web.servlet.view.InternalResourceViewResolver "><!--webroot The path to a specified folder-->< Property name= "prefix" value= "/web-inf/jsps/" ></property><!--view name suffix--><property name= "suffix" Value= ". jsp" ></property></bean><!--id= "Multipartresolver" must be Multipartresolver--><bean Id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" ><!-- Maxuploadsize: Maximum file Upload value in bytes--><property name= "maxuploadsize" value= "1024000" ></property></ Bean></beans>

The hibernate mapping file is:

<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration public        "-//hibernate/hibernate configuration DTD 3.0//en"        "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">

Now configure in Web. xml:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "Webapp_ ID "version=" 2.5 "> <context-param> <param-name>contextConfigLocation</param-name> < Param-value>classpath:applicationcontext.xml</param-value> </context-param> <!-- Configure Spring Start Listener entry-<listener> <listener-class> org.springframework.web.context.contextloaderlistener</listener-class></listener><!-- Configure SPRINGMVC to start the Dispatcherservlet Ingress--><!--Central Controller--><servlet><servlet-name>springmvc</ Servlet-name><servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param><param-name>contextconfiglocation</param-name&gT;<param-value>classpath:springmvc.xml</param-value></init-param><load-on-startup>1 </load-on-startup></servlet><filter><filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class><init-param ><param-name>encoding</param-name><param-value>utf-8</param-value></init-param ><init-param><param-name>forceencoding</param-name><param-value>true</ param-value></init-param></filter><!--encoding filter for JSP page--><filter-mapping> <filter-name>encodingfilter</filter-name><url-pattern>/*</url-pattern></ filter-mapping> <servlet-mapping><servlet-name>springMVC</servlet-name><!--struts wont use/* , in Springmvc, regardless of--><url-pattern>/</url-pattern></servlet-mapping></web-app>.
Now start the programming process:

User class:

Package Cn.com.domain;import Java.io.serializable;import Javax.persistence.column;import javax.persistence.Entity; Import Javax.persistence.generatedvalue;import Javax.persistence.id;import Javax.persistence.table;import Org.hibernate.annotations.genericgenerator;public class Users implements Serializable {private String id;private String Name;private string Pwd;public string GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String getpwd () {return pwd;} public void SetPwd (String pwd) {this.pwd = pwd;}}
The corresponding User.hbm.xml configuration file is:

<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

Iuserdao:

Package Cn.com.dao;import Cn.com.domain.users;public interface Iuserdao {public void AddUser (Users user);p ublic void UpdateUser (Users user);}
Iuserdaoimpl:

Package Cn.com.dao.impl;import Org.springframework.orm.hibernate3.hibernatetemplate;import Cn.com.dao.IUserDao; Import Cn.com.domain.users;public class Userdaoimpl implements Iuserdao {private hibernatetemplate hibernatetemplate; Public Hibernatetemplate Gethibernatetemplate () {return hibernatetemplate;} public void Sethibernatetemplate (Hibernatetemplate hibernatetemplate) {this.hibernatetemplate = HibernateTemplate;} public void AddUser (Users user) {this.hibernateTemplate.save (user);} public void UpdateUser (Users user) {this.hibernateTemplate.update (user);}}
Iuserservice:

Package Cn.com.service;import Cn.com.domain.users;public interface Iuserservice {public void AddUser (users users); public void UpdateUser (Users user);
Iuserserviceimpl:

Package Cn.com.service.impl;import Cn.com.dao.iuserdao;import Cn.com.domain.users;import Cn.com.service.iuserservice;public class Userserviceimpl implements Iuserservice {private Iuserdao userdao;public void AddUser (users) {This.userDao.addUser (users);} Public Iuserdao Getuserdao () {return userdao;} public void Setuserdao (Iuserdao userdao) {This.userdao = Userdao;} public void UpdateUser (Users user) {this.userDao.updateUser (user);}}
A tool class to write:

Serviceprovindercore:

Package Cn.com.container;import Org.springframework.context.applicationcontext;import org.springframework.context.support.classpathxmlapplicationcontext;/** * The primary purpose of this class is to load the spring configuration file * @author Administrator * */public class Serviceprovindercore {protected applicationcontext context;public void Load (String FileName) {context=new classpathxmlapplicationcontext (filename);}}

Serviceprovinder:

Package Cn.com.container;import Org.springframework.util.stringutils;public class Serviceprovinder {private static Serviceprovindercore sc;static{sc=new Serviceprovindercore (); Sc.load ("Applicationcontext.xml");} public static Object GetService (String beanname) {Object Bean=null;if (! Stringutils.hastext (Beanname)) {throw new RuntimeException ("The service name you want to access cannot be empty! ");} If the spring container contains Beannameif (Sc.context.containsBean (beanname)) {Bean=sc.context.getbean (beanname);} If the spring container does not contain Beannameif (bean==null) {throw new RuntimeException ("The service name you want to access [" +beanname+ "] does not Exist");} return bean;}}
Controller Usercontroller:

Package Cn.com.controller;import Java.util.uuid;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Cn.com.container.serviceprovinder;import Cn.com.dao.iuserdao;import cn.com.domain.users;import Cn.com.service.IUserService, @Controller @requestmapping ("/ User ") public class Usercontroller {@RequestMapping ("/tosuccess.do ") public String tosuccess () {System.out.println (" Success "); return" Success ";} @RequestMapping ("/toadd.do") public String Add () {return ' Add ';} @RequestMapping ("/tologin.do") public String login () {return ' login ';} @RequestMapping ("/tosave.do") public String Save (Users user) {System.out.println (User.getname ()); System.out.println (User.getpwd ()); String Id=uuid.randomuuid (). toString (). Replace ("-", "" "). substring (0,4); User.setid (ID); Serviceprovinder provinder=new Serviceprovinder (); Iuserservice userdao= (Iuserservice) Provinder.getService (" UserService "); Userdao.adduser (user); return" Success ";}}
In these packages and in the writing of each class, the overall structure is:

Now let's test it out:

add.jsp

Click Submit later:

The JSP page turns to:

Integration completed successfully.

The XML configuration file is used here for development, which is easier to do with annotations.

Spring+springmvc+hibernate integration, that's it.



Spring+springmvc+hibernate Consolidation Examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.