2013-02-15 55 views
0

我想用CRUD邏輯創建一個簡單的網頁,使用Spring MVCHibernate。 我創造了這個簡單的UserController中:實體沒有在Hibernate中更新

我的Spring配置[置頂]:

<?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:p="http://www.springframework.org/schema/p" 
    xmlns:c="http://www.springframework.org/schema/c" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> 

    <!-- Root Context: defines shared resources visible to all other web components --> 
    <context:annotation-config /> 
    <context:component-scan base-package="org.vdzundza.dao" /> 
    <context:component-scan base-package="org.vdzundza.service" /> 

    <bean id="propertiesConfig" 
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
     p:location="/WEB-INF/jdbc.properties" /> 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
     destroy-method="close"> 
     <property name="driverClassName" value="${jdbc.driverClassName}" /> 
     <property name="url" value="${jdbc.url}" /> 
     <property name="username" value="${jdbc.username}" /> 
     <property name="password" value="${jdbc.password}" /> 
    </bean> 

    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 
     lazy-init="true"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> 
       <prop key="hibernate.show_sql">true</prop> 
       <prop key="hibernate.hbm2ddl.auto">update</prop> 
       <prop key="hibernate.current_session_context_class">thread</prop> 
      </props> 
     </property> 
     <property name="packagesToScan" value="org.vdzundza.beans" /> 
    </bean> 
<tx:annotation-driven/> 
    <bean id="transactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory"><ref local="sessionFactory"/></property> 
    </bean> 
</beans> 

我的控制器:

package org.vdzundza.web; 

import java.util.Map; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.vdzundza.beans.User; 
import org.vdzundza.service.UserService; 

@Controller 
@RequestMapping("/user") 
public class UserController { 

    @Autowired 
    private UserService userService; 

    private static final Logger logger = LoggerFactory 
      .getLogger(UserController.class);  

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) 
    public String updateUserGet(Map<String, Object> map, @PathVariable("id") Long id){ 
     User user = userService.loadUser(id); 
     map.put("user", user); 
     return "edit"; 
    } 

    @RequestMapping(value = "/edit", method = RequestMethod.POST) 
    public String updateUserPost(@ModelAttribute("user") User user, BindingResult result){ 
     logger.info("update user: " + user.toString()); 
     userService.updateUser(user); 
     return "redirect:/user/index"; 
    } 
} 

我的UserDAO:

package org.vdzundza.dao; 

import java.util.List; 

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Transactional; 
import org.vdzundza.beans.User; 

@Repository 
@Transactional(value = "transactionManager") 
public class UserDAOImpl implements UserDao { 

    @Autowired 
    private SessionFactory sessionFactory; 

    private static final Logger logger = LoggerFactory 
      .getLogger(UserDAOImpl.class); 


    public void updateUser(User user) { 
     Session session = sessionFactory.getCurrentSession(); 
     Transaction tx = null; 
     try { 
      tx = session.beginTransaction(); 
      session.update(user); 
      tx.commit(); 

     } catch (RuntimeException e) { 
      tx.rollback(); 
     } 
    } 

    public User loadUser(Long id) { 
     Session session = sessionFactory.openSession(); 
     return (User) session.load(User.class, id); 
    } 
} 

和服務:

package org.vdzundza.service; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 

import org.vdzundza.beans.User; 
import org.vdzundza.dao.UserDao; 

@Service 
public class UserServiceImpl implements UserService { 

    @Autowired 
    private UserDao userDAO;   

    @Transactional 
    public void updateUser(User user) { 
     userDAO.updateUser(user); 

    } 

    @Transactional 
    public User loadUser(Long id) { 
     return userDAO.loadUser(id); 
    } 
} 

我簡單的形式更新:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 
<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>Update user</title> 
</head> 
<body> 
    <form:form method="post" 
     action="${pageContext.request.contextPath}/user/edit" 
     commandName="user"> 
     <table> 
      <tr> 
       <td><form:label path="firstName">First Name</form:label></td> 
       <td><form:input path="firstName" /></td> 
      </tr> 

      <tr> 
       <td><form:label path="lastName">Last Name</form:label></td> 
       <td><form:input path="lastName" /></td> 
      </tr> 

      <tr> 
       <td><form:label path="network">network</form:label></td> 
       <td><form:input path="network" /></td> 
      </tr> 
      <tr> 
       <td colspan="2"><input type="submit" value="update user" /></td> 
      </tr> 

     </table> 
    </form:form> 
</body> 
</html> 

爲什麼沒有我的 「UpdateUser兩個」(DAO)方法更新實體?

+2

爲什麼在你的DAO中使用編程事務處理?如果您的應用程序上下文已正確配置,那麼該類上的@Transactional註釋就足夠了。你可以發佈你的彈簧配置嗎? – zagyi 2013-02-15 15:22:22

+0

你的xml配置似乎對我很好。我希望,在'updateUser()'方法中刪除手動事務處理,並且只保留'sessionFactory.getCurrentSession()。update(user);'應該可以工作。 – zagyi 2013-02-15 15:46:30

+0

我刪除事務處理,它不適合我。 – BILL 2013-02-15 16:23:12

回答

0

我添加隱藏的元素來形成。

<form:hidden path="id"/> 
4

做一個後

session.flush(); 

沖水裝置的

tx.commit(); 

我們的目標是你,它們與數據庫中的會話持久對象的狀態同步。

如果更改對象的狀態,該狀態將不會反映在數據庫中。 在刷新hibernate時,將數據庫與對象的新狀態同步。

+0

不起作用。我想它不能通過控制器中的invoke方法loadUser。 – BILL 2013-02-15 16:24:52

相關問題