SpringMVC +Hibernate 学习实例

做了好久经的spring+hibernate 只是用spring管理hibernate,但一直没有研究SpringMVC +Hibetate,所以
最近有时间 准备用springMVC + Spring + Hibernate 自己作个例子(SrpingMVC 也属于Spring 为了与那些只用Spring管理Hibernate的有点区别所以没有取名Spring+Hibernate)。希望对大家有帮助。

一,采用工具:eclipse, 数据库 oracle.

二,必须包有:
        hibernate包:hibernate.jar,ehcache-1.1.jar,c3p0-0.8.5.2.jar,cglib-nodep-2.1.jar
        spring包:spring.jar,spring-web.jar
        common包:commons-lang.jar,commons-logging.jar,commons-collections.jar
        dom4j包:dom4j-1.6.jar
        junit包:junit.jar
        oracle 驱动包:ojdbc14.zip,不知道为什么tomcat 不认识这个包呢 非的要改成 ojdbc.jar
        jstl包:jstl.jar
        jta: jta.jar
          
三,hibernate映射文件是采用Middlegen-Hibernate-r5 从数据库生成,然后根据映射文件,生成对应数据库的javabean

        Middlegen-Hibernate-r5 配置说明:
        
        1,首先是下载  Middlegen-Hibernate-r5   地址: http://sourceforge.net/project/showfiles.php?group_id=40712&package_id=84728
        
        2,下载后,以下是需要修改的地方,build.xml中
        
                <!DOCTYPE project [
                    <!ENTITY database SYSTEM "file:./config/database/hsqldb.xml">
                ]>
                改成
                
                <!DOCTYPE project [
                    <!ENTITY database SYSTEM "file:./config/database/oracle.xml">
                ]>
        
        3修改Middlegen-Hibernate-r5\config\database\oracle.xml 的配置:
        
           <property environment="env"/>
        
           <property name="database.script.file"           value="${src.dir}/sql/${name}-oracle.sql"/>
           <property name="database.driver.file"           value="${env.ORACLE_HOME}/jdbc/lib/classes12.jar"/>
           <property name="database.driver.classpath"      value="${database.driver.file}"/>
           <property name="database.driver"                value="oracle.jdbc.driver.OracleDriver"/>
           <property name="database.url"                   value="jdbc:oracle:thin:@localhost:1521:<ORASID>"/>
           <property name="database.userid"                value="scott"/>
           <property name="database.password"              value="tiger"/>
           <property name="database.schema"                value=""/>
           <property name="database.catalog"               value=""/>
        
           <!--property name="jboss.datasource.mapping"       value="Oracle7"/-->
           <property name="jboss.datasource.mapping"       value="Oracle8"/>
           <!--property name="jboss.datasource.mapping"       value="Oracle9i"/-->   
           
           改成你自己的,如下是我的
             
           <property environment="env"/>
           <property name="database.script.file"           value="${src.dir}/sql/${name}-oracle.sql"/>
           <property name="database.driver.file"           value="D:/XTZH/XTZH_AH/公共组件/公共jar包/oracle/ojdbc14.zip"/>
           <property name="database.driver.classpath"      value="${database.driver.file}"/>
           <property name="database.driver"                value="oracle.jdbc.driver.OracleDriver"/>
           <property name="database.url"                   value="jdbc:oracle:thin:@localhost:1521:GCR"/>
           <property name="database.userid"                value="guocr"/>
           <property name="database.password"              value="123456"/>
           <property name="database.schema"                value="guocr"/>
           <property name="database.catalog"               value=""/>
           <property name="jboss.datasource.mapping"       value="Oracle9i"/>   
           
        4,修改 build.xml 下面的 middlegen 命令下面的

       <hibernate
          destination="${build.gen-src.dir}"
          package="com.guocr.forum.domain"
          genXDocletTags="false"
          genIntergratedCompositeKeys="false"
          javaTypeMapper="middlegen.plugins.hibernate.HibernateJavaTypeMapper"
       />
         package="com.guocr.forum.domain" 改称你自己的包名称
           这些配好后就可以用 ant 运行  middlegen 就可以生成映射文件了, 然后运行hbm2java 就可以生成对应的javabean 文件
         
四,生成映射文件和对应数据库中的java文件后,开始配置spring bean 管理配置文件。在这里由于时间问题就不多讲配置文件了, 如有问题可以给我消息联系。

            我在这里取名为config/ForumServiceBeans.xml            
            以下是全部配置文件。            
            <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
                "http://www.springframework.org/dtd/spring-beans.dtd">            
            <beans>                 
            <!-- 
              <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                    <property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
                    <property name="url"><value>jdbc:oracle:thin:@localhost:1521:GCR</value></property>
                    <property name="username"><value>guocr</value></property>-->
                    <!-- Make sure <value> tags are on same line - if they're not, 
                         authentication will fail -->
                    <!--  <property name="password"><value>123456</value></property>
                </bean> -->        
                           
                <bean id="dataSource"
                    class="com.mchange.v2.c3p0.ComboPooledDataSource"
                    destroy-method="close">
                    <property name="driverClass">
                        <value>oracle.jdbc.driver.OracleDriver</value>
                    </property>
                    <property name="jdbcUrl">
                        <value>jdbc:oracle:thin:@localhost:1521:GCR</value>
                    </property>
                    <property name="user">
                        <value>guocr</value>
                    </property>
                    <property name="password">
                        <value>123456</value>
                    </property>
                    <property name="minPoolSize">
                        <value>5</value>
                    </property>
                    <property name="maxPoolSize">
                        <value>20</value>
                    </property>
                    <property name="maxIdleTime">
                        <value>1800</value>
                    </property>
                </bean>                            
                
            <!-- Hibernate SessionFactory -->
            <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                <property name="dataSource"><ref local="dataSource"/></property>
                <property name="mappingResources">
                    <list>
                        <value>com/guocr/forum/domain/User.hbm.xml</value>
                    </list>
                </property>
                <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
                   <!--  <prop key="hibernate.hbm2ddl.auto">update</prop>-->
                </props>
                </property>
            </bean>            
            
            <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
            <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                <property name="sessionFactory"><ref local="sessionFactory"/></property>
            </bean>        
            
                <!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource)-->
                <!--
                <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
                -->        
                    
                <bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
                    <property name="transactionManager">
                        <ref bean="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>
                            <prop key="comeBackHistoryConfig*">
                                PROPAGATION_REQUIRED,-Exception
                            </prop>
                            <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
                            <prop key="add*">PROPAGATION_REQUIRED</prop>
                            <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
                        </props>
                    </property>
                </bean>        
                    
            <bean id="userDAOTarget" class="com.guocr.forum.dao.hiberante.impl.UserDAO">
                <property name="sessionFactory"><ref local="sessionFactory"/></property>
            </bean>   
                        
              <bean id="userDAO" parent="baseTransactionProxy">
                    <property name="target">
                        <ref local="userDAOTarget"/>
                    </property>
                </bean> 
                    
            <!-- 
            <bean id="userManagerTarget" class="org.appfuse.service.impl.UserManagerImpl">
                <property name="userDAO"><ref local="userDAO"/></property>
            </bean>
            -->
            <!-- 
            <bean id="userManager" 
                class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
                <property name="transactionManager"><ref local="transactionManager"/></property>
                <property name="target"><ref local="userManagerTarget"/></property>
                <property name="transactionAttributes">
                    <props>
                        <prop key="save*">PROPAGATION_REQUIRED</prop>
                        <prop key="remove*">PROPAGATION_REQUIRED</prop>
                        <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
                    </props>
                </property>
            </bean>
            -->
        </beans>
    

五,下面开始写Spring MVC 框架

 1、首先配置 web.xml
 
       <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
            <web-app>      
              <servlet>
                <servlet-name>action</servlet-name>
                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                <load-on-startup>1</load-on-startup>
              </servlet>
              <servlet-mapping>
                <servlet-name>action</servlet-name>
                <url-pattern>*.do</url-pattern>
              </servlet-mapping>
        </web-app>

        配完 web.xml 之后,spring会自动找 action-servlet.xml ,为什么 去找action-servlet.xml,其实是找/WEB-INF/<servlet-name>-servlet.xml,
        在这里我们的servlet-name是action,所以找action-servlet.xml.如果不希望让他自动去找 action-servlet.xml也可以自己指定,如下指定
        了Confing.xml 

          <servlet>
            <servlet-name>action</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>/WEB-INF/Config.xml</param-value>
            </init-param>
          </servlet>
2、
       我是按默认的去找action-servlet.xml 下面开始建action-servlet.xml
        这个是类似ForumServiceBeans.xml ,应该可以与ForumServiceBeans.xml 合在一起,还没有测。
        下面是我建的action-servlet.xml.

            <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
                "http://www.springframework.org/dtd/spring-beans.dtd">
              <beans>
                <!-- 
                <bean id="userController" class="org.appfuse.web.UserController">
                    <property name="userManager" ref="userManager"/>
                </bean>
                
                <bean id="userFormController" class="org.appfuse.web.UserFormController">
                    <property name="commandName" value="user"/>
                    <property name="validator" ref="beanValidator"/>
                    <property name="formView" value="userForm"/>
                    <property name="successView" value="redirect:users.html"/>
                    <property name="userManager" ref="userManager"/>
                </bean>
                  -->      
                <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>      
                    <property name="prefix" value="/work/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            
                <bean id="urlMapping"  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
                    <property name="mappings">
                        <props>
                           <prop key="/work/login.do">LoginAction</prop>
                        </props>
                    </property>
                </bean>
                
                <bean id="LoginAction"
                        class="com.guocr.forum.service.LoginAction">
                        <property name="commandClass">
                            <value>com.guocr.forum.domain.User</value>
                        </property>
                        <property name="fail_view">
                            <value>loginfail</value>
                        </property>
                        <property name="success_view">
                            <value>main</value>
                        </property>
                </bean>
                
            <!-- 
            <bean id="urlMapping"  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
                <property name="mappings">
                    <props>
                        <prop key="/users.html">userController</prop>
                        <prop key="/editUser.html">userFormController</prop>
                    </props>
                </property>
            </bean>    
            -->
            <!-- 
            <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
                <property name="basename" value="messages"/>
                <property name="useCodeAsDefaultMessage" value="true"/>
            </bean>
            
            <bean id="validatorFactory" class="org.springmodules.commons.validator.DefaultValidatorFactory">
                <property name="validationConfigLocations">
                    <list>
                        <value>/WEB-INF/validator-rules.xml</value>
                        <value>/WEB-INF/validation.xml</value>
                    </list>
                </property>
            </bean>
          
            <bean id="beanValidator" class="org.springmodules.commons.validator.DefaultBeanValidator">
                <property name="validatorFactory" ref="validatorFactory"/>
            </bean>
              -->
            </beans>

有时间再补详细点。

3、开始建jsp,java类等

   注册页面 register.jsp 

            <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
            <%
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            %>
            
            <html>
            <head>
            <TITLE>注册会员</TITLE> 
            <% request.setCharacterEncoding("GBK"); 
            %>
            </head>
            <body onload="">
            <form method="POST" action="login.do"  >
            <br>
            <table width="98%" cellpadding="2" cellspacing="1" class="blove" align="center"> 
                 <tr height="20"><td align="right">会员名:</td><td><input type="text" name="name" maxlength=100 ></td></tr>
                  <tr height="20" ><td align="right">密码:</td><td><input type="password" name="password" maxlength=255 ></td></tr>
                  <tr height="20" ><td align="right">确认密码:</td><td><input type="password" name="password_two" maxlength=255 ></td></tr>
             </table>
            <br>
                    <table width="20%" cellpadding="2" cellspacing="1" bgColor="F4F9FC" align="center"> 
                            <tr>                
                            <td><input type="submit" value="保存" name="B1"></td>
                               </tr>
                    </table>
            
            </form>
            </body>
            </html>

            bean 管理配置管理类 ForumServiceFactory
            
            package com.guocr.forum.service;
            
            import org.springframework.context.ApplicationContext;
            import org.springframework.context.support.FileSystemXmlApplicationContext;
            import com.guocr.forum.dao.hiberante.IUserDAO;
            
            /**
             * 2006-06-10
             *
             * <p>Title: BEAN 管理服务实现类 </p>
             * 
             * <p>Description: </p>
             * 
             * <p>Copyright: Copyright (c) 2005</p>
             * 
             * <p>Company: </p>
             * 
             * @author guocr
             * 
             * @version 1.0
             */
            public class ForumServiceFactory {                                    
                /** 应用程序内容 */
                private ApplicationContext factory = null;
            
                /** 服务工厂 */
                private static ForumServiceFactory instance;
            
                /** 指定配置文件路径 */
                private static final String FORUM_CLIENT_BEAN_FILE = "config/ForumServiceBeans.xml";
            
                private ForumServiceFactory() {
                    this.factory = new FileSystemXmlApplicationContext(
                            new String[] { FORUM_CLIENT_BEAN_FILE });
                }
            
                /**
                 * 返回工厂实例.
                 * 
                 * @return 工厂实例
                 */
                public static ForumServiceFactory getInstance() {
            
                    if (instance == null) {
                        instance = new ForumServiceFactory();
                    }
            
                    return instance;
                }
                
                public IUserDAO getUserDAO(){
                    
                    return (IUserDAO) this.factory
                    .getBean("userDAO");    
                    
                }
                
            }

            package com.guocr.forum.service;
            
            import java.text.SimpleDateFormat;
            import java.util.Date;
            
            import org.springframework.validation.BindException;
            import org.springframework.web.servlet.ModelAndView;
            import org.springframework.web.servlet.mvc.SimpleFormController;
            
            import com.guocr.forum.domain.User;
            
            /**
             * 2006-06-12
             *
             * <p>Title: 用户基本信息业务类 </p>
             * 
             * <p>Description: </p>
             * 
             * <p>Copyright: Copyright (c) 2005</p>
             * 
             * <p>Company: </p>
             * 
             * @author guocr
             * 
             * @version 1.0
             */            
            
            public class LoginAction extends SimpleFormController {
            
                public void LoginAction(){
            
                } 
                private String fail_view;
            
                private String success_view;
            
                public String getFail_view() {
                    return fail_view;
                }
            
                public void setFail_view(String fail_view) {
                    this.fail_view = fail_view;
                }
            
                public String getSuccess_view() {
                    return success_view;
                }
            
                public void setSuccess_view(String success_view) {
                    this.success_view = success_view;
                }
                
                protected ModelAndView onSubmit(Object cmd, BindException ex)
                throws Exception {
                    
                    User user =(User)cmd;
                    System.out.println("user==="+user.getName());
                    System.out.println("password==="+user.getPassword());
                    //user.setRegisterdate("2006-06-11 09:46:50");
                    //Date b=new Date();
                    //user.setRegisterdate(b.toLocaleString());
                    Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                user.setRegisterdate(sdf.format(date));              
                    ForumServiceFactory.getInstance().getUserDAO().saveUser(user);
                    System.out.println("this.getSuccessView()"+this.getSuccessView());
                    
                    System.out.println("getSuccess_view"+this.getSuccess_view());
                    return new ModelAndView(this.getSuccess_view());
                }
                
            }


            package com.guocr.forum.dao.hiberante;
            import java.util.List;
            
            import com.guocr.forum.domain.User;
            
            /**
             * 2006-06-10
             *
             * <p>Title: 用户基本信息 </p>
             * 
             * <p>Description: </p>
             * 
             * <p>Copyright: Copyright (c) 2005</p>
             * 
             * <p>Company: </p>
             * 
             * @author guocr
             * 
             * @version 1.0
             */
            
            public interface IUserDAO {
                
                /**
                 * 返回用户信息
                 * @param userName 用户姓名
                 * @return 返回用户信息
                 * @throws Exception
                 */
                public User  getUser(String userName)throws Exception;
                
                /**
                 * 返回全部用户基本信息
                 * @return
                 * @throws Exception
                 */
                public List getUsers() throws Exception;
               
                /**
                 * 保存用户
                 * @throws Exception
                 */
                public void saveUser(User user) throws Exception;
                
                /**
                 * 修改用户信息
                 * @throws Exception
                 */
                public void updateUser (User user) throws Exception;
                
            }



            package com.guocr.forum.dao.hiberante.impl;
            
            import java.util.List;
            
            import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
            
            import com.guocr.forum.dao.hiberante.IUserDAO;
            import com.guocr.forum.domain.User;
            
            /**
             * 2006-06-10
             *
             * <p>Title: 用户基本信息实现类 </p>
             * 
             * <p>Description: </p>
             * 
             * <p>Copyright: Copyright (c) 2005</p>
             * 
             * <p>Company: </p>
             * 
             * @author guocr
             * 
             * @version 1.0
             */
            
            public class UserDAO extends HibernateDaoSupport implements IUserDAO {
            
                public User getUser(String userName) throws Exception {
                    User user = (User)this.getHibernateTemplate().get(User.class,userName);
                    return user;
                }
            
                public List getUsers() throws Exception {
                    
                    return null;
                }
            
                public void saveUser(User user) throws Exception {
                    this.getHibernateTemplate().save(user);
            
                }
            
                public void updateUser(User user) throws Exception {
                    this.getHibernateTemplate().update(user);            
                }            
            }

      最后跳转的页面是 /work/main.jsp,这个页面 你可以随便了。好了先到这里,希望对你有帮助。还有什么问题可以给我发JR消息。

你可能感兴趣的:(Hibernate)