spring+springmvc+hibernate整合實例

上篇博文中寫了spring與springmvc的整合,而這一篇則是又加上了hibernate。

與上次一樣,這一次仍然是先導入jar包,這一次則要加入hibernate中的jar包,如下圖所示:

 

同時再新建兩個源文件夾,一個爲config,一個爲test,分別存放配置文件與測試用例,現在來進行spring,springmvc以及hibernate的配置。

新建spring-hibernate.xml,applicationContext.xml,springmvc.xml,hibernate.cfg.xml四個配置文件,現在來對這四個配置文件進行配置。

spring-hibernate.xml:

[html] view plain copy print?

1. <?xml version="1.0" encoding="UTF-8"?>  

2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [  

3. <!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">  

4. ]>  

5. <beans>  

6.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  

7.         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  

8.         <property name="url" value="jdbc:mysql://localhost:3306/contacts"></property>  

9.         <property name="username" value="root"/>  

10.         <property name="password" value="root"/>  

11.     </bean>  

12.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  

13.         <property name="dataSource" ref="dataSource"></property>  

14.         <property name="hibernateProperties">  

15.             <props>  

16.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  

17.                 <prop key="show_sql">true</prop>  

18.                 <prop key="hibernate.show_sql">true</prop>  

19.                 <prop key="hiberante.format_sql">true</prop>  

20.             </props>  

21.         </property>  

22.          <property name="configLocations">  

23.             <list>  

24.                 <value>  

25.                     classpath:hibernate.cfg.xml  

26.                 </value>  

27.             </list>  

28.         </property>  

29.         <!-- 註解掃描的包 -->  

30.     <!-- <property name="annotatedClasses">  

31.         <list>  

32.             <value></value>  

33.         </list>  

34.     </property> -->  

35.     </bean>  

36.     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  

37.         <property name="sessionFactory" ref="sessionFactory"></property>  

38.     </bean>  

39.     <bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true" lazy-init="true">  

40.         <property name="transactionManager" ref="transactionManager"></property>  

41.         <property name="transactionAttributes">  

42.             <props>  

43.                 <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>  

44.                 <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>  

45.                 <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>  

46.             </props>  

47.         </property>  

48.     </bean>  

49.     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">  

50.         <property name="sessionFactory">  

51.             <ref bean="sessionFactory"></ref>  

52.         </property>  

53.     </bean>  

54. </beans>  

 

applicationContext.xml:

[html] view plain copy print?

1. <?xml version="1.0" encoding="UTF-8"?>  

2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [  

3. <!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">  

4. ]>  

5. <beans>  

6.     <import resource="spring-hibernate.xml"></import>  

7.     <bean id="userDao" class="cn.com.dao.impl.UserDaoImpl">  

8.         <property name="hibernateTemplate" ref="hibernateTemplate"></property>  

9.     </bean>  

10.     <bean id="userService" class="cn.com.service.impl.UserServiceImpl">  

11.         <property name="userDao" ref="userDao"></property>  

12.     </bean>  

13. </beans>  

springmvc.xml:

[html] view plain copy print?

1. <?xml version="1.0" encoding="UTF-8"?>  

2. <beans xmlns="http://www.springframework.org/schema/beans"  

3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  

4.     xmlns:context="http://www.springframework.org/schema/context"  

5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  

6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   

7.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   

8.         http://www.springframework.org/schema/mvc   

9.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   

10.         http://www.springframework.org/schema/context   

11.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   

12.         http://www.springframework.org/schema/aop   

13.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   

14.         http://www.springframework.org/schema/tx   

15.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">  

16.   

17.     <!-- mvc的註解驅動 -->  

18.     <mvc:annotation-driven />  

19.     <!-- 一旦有掃描器的定義mvc:annotation-driven不需要,掃描器已經有了註解驅動的功能 -->  

20.     <context:component-scan base-package="cn.com.controller" />  

21.   

22.   

23.     <!-- 前綴+ viewName +後綴 -->  

24.     <bean  

25.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  

26.         <!-- webroot到某一指定的文件夾的路徑 -->  

27.         <property name="prefix" value="/WEB-INF/jsps/"></property>  

28.         <!-- 視圖名稱的後綴 -->  

29.         <property name="suffix" value=".jsp"></property>  

30.     </bean>  

31.     <!-- id="multipartResolver"必須是multipartResolver -->  

32.     <bean id="multipartResolver"  

33.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  

34.         <!-- maxUploadSize:文件上傳的最大值以byte爲單位 -->  

35.         <property name="maxUploadSize" value="1024000"></property>  

36.     </bean>  

37. </beans>  

 

hibernate映射文件爲:

[html] view plain copy print?

1. <?xml version='1.0' encoding='utf-8'?>  

2. <!DOCTYPE hibernate-configuration PUBLIC  

3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  

4.         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  

5. <hibernate-configuration>  

6.     <session-factory>  

7.         <mapping resource="cn/com/domain/Users.hbm.xml"></mapping>  

8.     </session-factory>  

9. </hibernate-configuration>  

 

現在在web.xml中進行配置:

[html] view plain copy print?

1. <?xml version="1.0" encoding="UTF-8"?>  

2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  

4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  

5.     id="WebApp_ID" version="2.5">  

6.     <context-param>  

7.         <param-name>contextConfigLocation</param-name>  

8.         <param-value>classpath:applicationContext.xml</param-value>  

9.     </context-param>  

10.     <!-- 配置spring啓動listener入口 -->  

11.     <listener>  

12.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  

13.     </listener>  

14.       

15.     <!-- 配置springmvc啓動dispatcherServlet入口 -->  

16.     <!-- 中央控制器 -->  

17.     <servlet>  

18.         <servlet-name>springMVC</servlet-name>  

19.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  

20.         <init-param>  

21.             <param-name>contextConfigLocation</param-name>  

22.             <param-value>classpath:springmvc.xml</param-value>  

23.         </init-param>  

24.         <load-on-startup>1</load-on-startup>  

25.     </servlet>  

26.       

27.     <filter>  

28.         <filter-name>encodingFilter</filter-name>  

29.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  

30.         <init-param>  

31.             <param-name>encoding</param-name>  

32.             <param-value>UTF-8</param-value>  

33.         </init-param>  

34.         <init-param>  

35.             <param-name>forceEncoding</param-name>  

36.             <param-value>true</param-value>  

37.         </init-param>  

38.     </filter>  

39.     <!-- encoding filter for jsp page -->  

40.     <filter-mapping>  

41.         <filter-name>encodingFilter</filter-name>  

42.         <url-pattern>/*</url-pattern>  

43.     </filter-mapping>  

44.    

45.       

46.     <servlet-mapping>  

47.         <servlet-name>springMVC</servlet-name>  

48.         <!-- struts習慣使用/*,在springmvc不管用 -->  

49.         <url-pattern>/</url-pattern>  

50.     </servlet-mapping>  

51.       

52.       

53.       

54. </web-app>  

現在開始編程過程:

User類:

[java] view plain copy print?

1. package cn.com.domain;  

2.   

3. import java.io.Serializable;  

4.   

5. import javax.persistence.Column;  

6. import javax.persistence.Entity;  

7. import javax.persistence.GeneratedValue;  

8. import javax.persistence.Id;  

9. import javax.persistence.Table;  

10.   

11. import org.hibernate.annotations.GenericGenerator;  

12.   

13. public class Users implements Serializable {  

14.   

15.     private String id;  

16.   

17.     private String name;  

18.   

19.     private String pwd;  

20.     public String getId() {  

21.         return id;  

22.     }  

23.     public void setId(String id) {  

24.         this.id = id;  

25.     }  

26.     public String getName() {  

27.         return name;  

28.     }  

29.     public void setName(String name) {  

30.         this.name = name;  

31.     }  

32.     public String getPwd() {  

33.         return pwd;  

34.     }  

35.     public void setPwd(String pwd) {  

36.         this.pwd = pwd;  

37.     }  

38. }  

對應的User.hbm.xml配置文件爲:

[html] view plain copy print?

1. <?xml version="1.0" encoding="utf-8"?>  

2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  

3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  

4. <hibernate-mapping>  

5.     <class name="cn.com.domain.Users" table="users">  

6.         <id name="id" type="java.lang.String">  

7.             <column name="id"></column>  

8.         </id>  

9.         <property name="name" type="java.lang.String" length="20"></property>  

10.         <property name="pwd" type="java.lang.String" length="20"></property>  

11.     </class>  

12. </hibernate-mapping>  

 

IUserDao:

[java] view plain copy print?

1. package cn.com.dao;  

2.   

3. import cn.com.domain.Users;  

4.   

5. public interface IUserDao {  

6.   

7.     public void addUser(Users user);  

8.   

9.     public void updateUser(Users user);  

10. }  

IUserDaoImpl:

[java] view plain copy print?

1. package cn.com.dao.impl;  

2.   

3. import org.springframework.orm.hibernate3.HibernateTemplate;  

4.   

5. import cn.com.dao.IUserDao;  

6. import cn.com.domain.Users;  

7.   

8. public class UserDaoImpl implements IUserDao {  

9.   

10.     private HibernateTemplate hibernateTemplate;  

11.   

12.     public HibernateTemplate getHibernateTemplate() {  

13.         return hibernateTemplate;  

14.     }  

15.   

16.     public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {  

17.         this.hibernateTemplate = hibernateTemplate;  

18.     }  

19.   

20.     public void addUser(Users user) {  

21.         this.hibernateTemplate.save(user);  

22.     }  

23.   

24.     public void updateUser(Users user) {  

25.         this.hibernateTemplate.update(user);  

26.     }  

27.   

28. }  

IUserService:

[java] view plain copy print?

1. package cn.com.service;  

2.   

3. import cn.com.domain.Users;  

4.   

5. public interface IUserService {  

6.   

7.     public void addUser(Users users);  

8.   

9.     public void updateUser(Users user);  

10. }  

IUserServiceImpl:

[java] view plain copy print?

1. package cn.com.service.impl;  

2.   

3.   

4. import cn.com.dao.IUserDao;  

5. import cn.com.domain.Users;  

6. import cn.com.service.IUserService;  

7.   

8. public class UserServiceImpl implements IUserService {  

9.   

10.     private IUserDao userDao;  

11.     public void addUser(Users users) {  

12.         this.userDao.addUser(users);  

13.     }  

14.     public IUserDao getUserDao() {  

15.         return userDao;  

16.     }  

17.     public void setUserDao(IUserDao userDao) {  

18.         this.userDao = userDao;  

19.     }  

20.   

21.     public void updateUser(Users user) {  

22.         this.userDao.updateUser(user);  

23.     }  

24.   

25. }  

編寫的一個工具類:

ServiceProvinderCore:

[java] view plain copy print?

1. package cn.com.container;  

2.   

3. import org.springframework.context.ApplicationContext;  

4. import org.springframework.context.support.ClassPathXmlApplicationContext;  

5.   

6. /** 

7.  * 該類的主要目的是加載spring配置文件 

8.  * @author Administrator 

9.  * 

10.  */  

11. public class ServiceProvinderCore {  

12.     protected ApplicationContext context;  

13.   

14.     public void load(String filename){  

15.         context=new ClassPathXmlApplicationContext(filename);  

16.     }  

17. }  

 

ServiceProvinder:

[java] view plain copy print?

1. package cn.com.container;  

2.   

3. import org.springframework.util.StringUtils;  

4.   

5. public class ServiceProvinder {  

6.     private static ServiceProvinderCore sc;  

7.     static{  

8.         sc=new ServiceProvinderCore();  

9.         sc.load("applicationContext.xml");  

10.     }  

11.   

12.     public static Object getService(String beanName){  

13.         Object bean=null;  

14.         if(!StringUtils.hasText(beanName)){  

15.             throw new RuntimeException("您要訪問的服務名不能爲空!");  

16.         }  

17.         //如果spring容器中包含beanName  

18.         if(sc.context.containsBean(beanName)){  

19.             bean=sc.context.getBean(beanName);  

20.         }  

21.         //如果spring容器中不包含beanName  

22.         if(bean==null){  

23.             throw new RuntimeException("您要訪問的服務名稱["+beanName+"]不存在");  

24.         }  

25.         return bean;  

26.     }  

27. }  

控制器UserController:

[java] view plain copy print?

1. package cn.com.controller;  

2.   

3. import java.util.UUID;  

4.   

5. import org.springframework.stereotype.Controller;  

6. import org.springframework.web.bind.annotation.RequestMapping;  

7.   

8. import cn.com.container.ServiceProvinder;  

9. import cn.com.dao.IUserDao;  

10. import cn.com.domain.Users;  

11. import cn.com.service.IUserService;  

12.   

13. @Controller  

14. @RequestMapping("/user")  

15. public class UserController {  

16.   

17.     @RequestMapping("/toSuccess.do")  

18.     public String toSuccess(){  

19.         System.out.println("success");  

20.         return "success";  

21.     }  

22.   

23.     @RequestMapping("/toAdd.do")  

24.     public String add(){  

25.         return "add";  

26.     }  

27.   

28.     @RequestMapping("/toLogin.do")  

29.     public String login(){  

30.         return "login";  

31.     }  

32.   

33.     @RequestMapping("/toSave.do")  

34.     public String save(Users user){  

35.         System.out.println(user.getName());  

36.         System.out.println(user.getPwd());  

37.         String id=UUID.randomUUID().toString().replace("-""").substring(0,4);  

38.         user.setId(id);  

39.         ServiceProvinder provinder=new ServiceProvinder();  

40.         IUserService userDao=(IUserService) provinder.getService("userService");  

41.         userDao.addUser(user);  

42.         return "success";  

43.     }  

44. }  

在這些包以及各個類的編寫中,總體結構爲:

 

現在來進行測試:

add.jsp

 

點擊提交以後:

 

jsp頁面轉向爲:

 

成功完成整合。

在這裏使用的是xml配置的文件來進行開發,如果是使用註解來做的話會更爲簡單一些。

spring+springmvc+hibernate的整合,就是這樣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章