我想使用 Spring MVC 和 Hibernate 创建一个包含CRUD逻辑的简单网页。 我创建了这个简单的UserController:
我的春季配置[上]:
<?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)方法不更新实体?
答案 0 :(得分:4)
做一个
session.flush();
之后
tx.commit();
刷新机制的目标是将会话中持久对象的状态与数据库同步。
如果更改对象的状态,则状态不会反映在数据库中。 在flush hibernate上,将数据库与对象的新状态同步。
答案 1 :(得分:0)
我将隐藏元素添加到表单中。
<form:hidden path="id"/>