hibernate和spring mvc组合​​无法正常工作

时间:2015-09-21 11:29:58

标签: java spring hibernate spring-mvc

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

我的项目结构>>>

enter code here

我的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>

我的申请上下文&gt;&gt;

    <?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&gt;&gt;

    <?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&gt;&gt;&gt;

    <?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>

我的用户控制器&gt;&gt;&gt;

    @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 Class(pojo)&gt;&gt;&gt;

    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&gt;&gt;&gt;

    <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&gt;&gt;&gt;

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

1 个答案:

答案 0 :(得分:0)

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

  

强制此会话刷新。必须在单位结束时调用   在提交交易和结束会议之前工作   (取决于flush-mode,Transaction.commit()调用此方法)。   刷新是同步底层持久性的过程   持久存在的商店。

     

抛出:HibernateException - 表示刷新会话的问题   或与数据库交谈。

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

P.S。:另外,通常,将与数据库相关的逻辑合并到控制器中并不是一个好习惯,您需要遵循服务/ DAO以确保它们易于维护以满足未来的需求。如果它只是为了你的学习目的,那很好,你可以这样做。