Spring和Hibernate不将我的记录保存在数据库中
Posted
技术标签:
【中文标题】Spring和Hibernate不将我的记录保存在数据库中【英文标题】:Spring & Hibernate don't save my records in database 【发布时间】:2013-12-12 01:03:37 【问题描述】:我已经阅读了许多与我相同的问题的主题,但没有解决,所以我决定在这里写。
问题是当我想在我的项目中编辑或删除记录时,用Java实现的每个功能似乎都可以正常运行,但数据库中没有任何变化。 例如,在我的项目中,我有一个名为“Oddzial”的模型(英文是部门)。 我可以将新的 Oddzial(部门)添加到数据库中,然后我会看到更改。但是,如果我想删除所有内容,则没有任何错误,而且数据库中也没有任何更改。应该删除的记录仍在数据库中。
这是我的文件:
型号:
@Entity
@Table(name="oddzial")
public class Oddzial implements Serializable
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer oddzial_id;
@Size(min=3, max=25, message="test message.")
private String miasto;
@Size(min=5, max=50, message="test message.")
private String ulica;
public Integer getOddzial_id()
return oddzial_id;
public void setOddzial_id(Integer oddzial_id)
this.oddzial_id = oddzial_id;
public Integer getId()
return oddzial_id;
public void setId(Integer id_oddzial)
this.oddzial_id = id_oddzial;
public String getMiasto()
return miasto;
public void setMiasto(String miasto)
this.miasto = miasto;
public String getUlica()
return ulica;
public void setUlica(String ulica)
this.ulica = ulica;
@Override
public String toString()
return "[" + oddzial_id + "] " + ulica + " " + miasto;
这是 Oddzial 的 DAO:
@Repository
public class OddzialDAOImpl implements OddzialDAO
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession()
return sessionFactory.getCurrentSession();
public void addOddzial(Oddzial oddzial)
getCurrentSession().save(oddzial);
public void updateOddzial(Oddzial oddzial)
Oddzial oddzialToUpdate = getOddzial(oddzial.getId());
oddzialToUpdate.setMiasto(oddzial.getMiasto());
oddzialToUpdate.setUlica(oddzial.getUlica());
getCurrentSession().update(oddzialToUpdate);
public Oddzial getOddzial(int id)
Oddzial oddzial = (Oddzial) getCurrentSession().get(Oddzial.class, id);
return oddzial;
public void deleteOddzial(int id)
Oddzial oddzial = getOddzial(id);
if (oddzial != null)
getCurrentSession().delete(oddzial);
@SuppressWarnings("unchecked")
public List<Oddzial> getOddzialy()
return getCurrentSession().createQuery("from Oddzial").list();
这里是 OddzialService:
@Service
@Transactional
public class OddzialServiceImpl implements OddzialService
@Autowired
private OddzialDAO oddzialDAO;
@Override
public void addOddzial(Oddzial oddzial)
oddzialDAO.addOddzial(oddzial);
@Override
public void updateOddzial(Oddzial oddzial)
oddzialDAO.updateOddzial(oddzial);
@Override
public Oddzial getOddzial(int id)
return oddzialDAO.getOddzial(id);
@Override
public void deleteOddzial(int id)
oddzialDAO.deleteOddzial(id);
@Override
public List<Oddzial> getOddzialy()
return oddzialDAO.getOddzialy();
这里是控制器:
@Controller
@RequestMapping(value="/oddzial")
public class OddzialController
@Autowired
private OddzialService oddzialService;
@RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addOddzialPage()
ModelAndView modelAndView = new ModelAndView("add-oddzial-form");
modelAndView.addObject("oddzial", new Oddzial());
return modelAndView;
@RequestMapping(value="/add", method=RequestMethod.POST)
public String addingOddzial(@ModelAttribute @Valid Oddzial oddzial, BindingResult result)
if(result.hasErrors())
return "add-oddzial-form";
oddzialService.addOddzial(oddzial);
String message = "Oddział został pomyślnie dodany do bazy.";
return "list-of-oddzials";
@RequestMapping(value="/list")
public ModelAndView listOfOddzials()
ModelAndView modelAndView = new ModelAndView("list-of-oddzials");
List<Oddzial> oddzials = oddzialService.getOddzialy();
modelAndView.addObject("oddzials", oddzials);
return modelAndView;
@RequestMapping(value="/edit/id", method=RequestMethod.GET)
public ModelAndView editOddzialPage(@PathVariable Integer id)
ModelAndView modelAndView = new ModelAndView("edit-oddzial-form");
Oddzial oddzial = oddzialService.getOddzial(id);
modelAndView.addObject("oddzial",oddzial);
return modelAndView;
@RequestMapping(value="/edit/id", method=RequestMethod.POST)
public ModelAndView edditingOddzial(@ModelAttribute Oddzial oddzial, @PathVariable Integer id)
ModelAndView modelAndView = new ModelAndView("home");
oddzialService.updateOddzial(oddzial);
String message = "Dane zostały zmodyfikowane.";
modelAndView.addObject("message", message);
return modelAndView;
@RequestMapping(value="/delete/id", method=RequestMethod.GET)
public ModelAndView deleteOddzial(@PathVariable Integer id)
ModelAndView modelAndView = new ModelAndView("home");
oddzialService.deleteOddzial(id);
String message = "Oddział został usunięty.";
modelAndView.addObject("message", message);
return modelAndView;
我的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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:flow="http://www.springframework.org/schema/webflow-config"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/tutorial" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="pl.carrental" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="passwordEncoder"
class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<constructor-arg value="256" />
</bean>
<bean id="saltSource"
class="org.springframework.security.authentication.dao.ReflectionSaltSource">
<property name="userPropertyToUse" value="username" />
</bean>
<!-- <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry"></property> </bean> <bean
class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"> <property
name="flowExecutor" ref="flowExecutor"></property> </bean> <flow:flow-executor
id="flowExecutor" flow-registry="flowRegistry" /> <flow:flow-registry id="flowRegistry"
base-path="/WEB-INF/flows"> <flow:flow-location-pattern value="/**/*-flow.xml"
/> </flow:flow-registry> -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan
base-package="pl.carrental" />
web.xml的内容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>localizationFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
提前感谢您的帮助
【问题讨论】:
所以你可以添加记录但不能修改或删除它们?我注意到您在 Hibernate 属性中将show_sql
设置为 true
。当您尝试删除/修改记录时,您能看到 SQL Hibernate 生成了什么吗?
数据库中是否存在具有该 ID 的对象,如果您在 getCurrentSession().delete() 上设置断点,它会被命中吗?
【参考方案1】:
已解决。行:
<tx:annotation-driven transaction-manager="transactionManager" />
必须在 servlet-context.xml 中。不像我的情况那样在 root-config.xml 中。现在事务已提交,我可以删除和更新记录。
【讨论】:
以上是关于Spring和Hibernate不将我的记录保存在数据库中的主要内容,如果未能解决你的问题,请参考以下文章
Spring/Hibernate GenerationType.AUTO 的数据库备份问题
使用 Hibernate + Spring 进行缓存 - 一些问题
如何在spring boot和hibernate中计算特定id的记录