繁体   English   中英

休眠和春季MVC组合无法正常工作

[英]hibernate and spring mvc combination is not working properly

我正在用休眠学习Spring MVC。 我尝试了一个教程,其中显示了反向工程和hbm.xml。 但是我想为此使用带注释的域类。 为此,我正在尝试一些但没有运气。 我已经在netbeans中使用spring和hibernate框架进行了一个Web项目。 当我提交表单时,它可以正常工作并重定向到其他页面,但数据不会保存。 有人可以帮我吗? 这是我在下面的尝试::

我的项目结构>>>

在这里输入代码

我的dispatcher-servlet.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       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.1.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="com.controller" />     
    <mvc:annotation-driven/>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

</beans>

我的应用程序上下文>>

    <?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:p="http://www.springframework.org/schema/p"
       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.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">



</beans>

我的web.xml >>

    <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

我的hibernate.cfg.xml >>>

    <?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">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/springhibernate?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.jdbc.batch_size">50</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
  </session-factory>
</hibernate-configuration>

我的用户控制器>>>

    @Controller
public class UserController {

   private static SessionFactory factory;

    @RequestMapping(value="/getForm", method = RequestMethod.GET)
    public ModelAndView getDemoForm(){        
        ModelAndView model = new ModelAndView("demoForm");        
        return model;
    }

    @RequestMapping(value = "/submitDemoForm.html", method = RequestMethod.POST)
    public ModelAndView submitAdmissionForm(@ModelAttribute("employee") EmployeeAnnotation employee) {
        try {
            factory = new AnnotationConfiguration().
                    configure().
                    //addPackage("com.xyz") //add package if used.
                    addAnnotatedClass(EmployeeAnnotation.class).
                    buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }

        Session session = factory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            employeeID = (Integer) session.save(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }

        ModelAndView model = new ModelAndView("demoFormSuccess");

        return model;
    }

}

我的EmployeeAnnotation类(pojo)>>>

    import javax.persistence.*;

@Entity
@Table(name = "employee_annotation")
public class EmployeeAnnotation {
   @Id @GeneratedValue
   @Column(name = "id")
   private int id;

   @Column(name = "first_name")
   private String firstName;

   @Column(name = "last_name")
   private String lastName;

   @Column(name = "salary")
   private int salary;  

   public EmployeeAnnotation() {}
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

我的demoForm.jsp >>>

    <form action="/springMvcHibernate/submitDemoForm.html" method="post">

    <p>
      Firts Name : <input type="text" name="firstName"/>
    </p>
    <p>
      Last Name : <input type="text" name="lastName"/>
    </p>
    <p>
            Salary : <input type="number" name="salary"/>
    </p>
    <input type="submit" value="Submit"/>

</form>

我的demoFormSuccess.jsp >>>

<body>
    <h1>ID is :: ${employee.id}</h1>
</body>

您必须在调用Transaction commit()之前在submitAdmissionForm()方法中调用session.flush() ,请查看以下来自Hibernate API (强调我的)的建议

强制刷新该会话。 在提交事务并关闭会话之前 ,必须在工作单元的末尾调用(取决于刷新模式,Transaction.commit()会调用此方法)。 刷新是将基础持久性存储与内存中保持的可持久状态进行同步的过程。

抛出:HibernateException-指示刷新会话或与数据库对话时出现问题。

https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#flush()

PS:此外,通常,将与daatabase相关的逻辑合并到控制器中也不是一个好习惯,您需要遵循服务/ DAO,以确保它们易于维护以适应将来的需求。 如果这只是为了您的学习目的,那就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM