Spring - 数据库未更新

时间:2015-02-01 19:40:48

标签: java spring hibernate postgresql session

我正在用Java开发Spring Framework中的Web应用程序。我的Postgres数据库遇到了一些问题。我尝试在db中的User表中添加一条记录。数据从注册表单字段中收集。它保存得很好,包含在User对象中,一切看起来都很好。除了事实,当我使用pgAdmin III浏览时,我在数据库中看不到任何新行。这是我的添加逻辑:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User user, BindingResult result, HttpServletRequest request) {
   user.setEnabled(true);
   user.setPosts(0);
   System.out.println(user.getId());

   ArrayList <User> list =  (ArrayList<User>) userService.listUser();
   System.out.println(list.size());

   //if (user.getId()==0)
   userService.addUser(user);
//       else
//         userService.editUser(user);

   return "redirect:register.html";
}

我是通过调用userService中定义的方法来实现的,该方法在我的userDAO实现类中调用一个方法:

public void addUser(User user) {
    sessionFactory.getCurrentSession().save(user);        
}
但是,有趣的是,当我检查用户列表的大小时,通过调用另一个userDAO方法:

public List<User> listUser() {

    return sessionFactory.getCurrentSession().createQuery("from User order by _id").list();
}

结果非零,并且每次添加用户时都会增加。这意味着,数据必须存储在某个地方,我不知道在哪里。 Hibernate访问在spring-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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


<context:annotation-config />
<context:component-scan base-package="dao" />
<context:component-scan base-package="service" />
<context:component-scan base-package="controllers" />

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <!--Don't add suffix or prefix like you do with .jsp files -->
    <property name="viewClass"
        value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>

<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <property name="definitions">
        <value>/WEB-INF/tiles.xml</value>
    </property>
</bean>

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

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    lazy-init="true">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url"
        value="jdbc:postgresql://localhost:5432/postgres?characterEncoding=utf-8" />
    <property name="username" value="postgres" />
    <property name="password" value="postgres" />
</bean>

<bean id="hibernateSessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.default_schema">spring3</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.generate_statistics">false</prop>
        </props>
    </property>

    <property name="packagesToScan">
        <list>
            <value>domain</value>
        </list>
    </property>

</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>

<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>

<bean id="localeChangeInterceptor"
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>

<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

<bean id="handlerMapping"
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
        <ref bean="localeChangeInterceptor" />
    </property>
</bean>

我也很确定,用户名,密码和架构在这里是正确的。此外,数据在STS的数据源资源管理器中正确显示。有任何想法吗?我真的不知道在哪里寻找。

更新: 我做交易的班级有适当的注释,但它仍然不起作用:

界面:

@Transactional(propagation = Propagation.REQUIRED)  
public interface UserService {

    public void addUser(User user);
    public void editUser(User user);
    public List<User> listUser();
    public void removeUser (int id);
    public User getUser(int id);

}

及其实施:

@Service
@Transactional
public class UserServiceImpl implements UserService {

@Autowired
UserDAO userDAO;

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

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

@Transactional
public List<User> listUser() {

    return userDAO.listUser();
}

@Transactional
public void removeUser(int id) {
    userDAO.removeUser(id);
}

@Transactional
public User getUser(int id) {
    return userDAO.getUser(id);
}

}

2 个答案:

答案 0 :(得分:0)

我想你有一个问题,因为你没有冲洗你的会话。

如果您没有刷新会话,数据将保留在休眠会话中,但不会保留在最终状态,即不在数据库中。

由于你正在使用Spring,只需在控制器方法上放置@Transactional注释就足够了:它自动处理会话,提交和刷新。

答案 1 :(得分:0)

好的,从输入中可以清楚地看出,您没有配置为手动或自动提交事务。你可以通过以下方式实现。

  

手动设置:

在您的DAO类中,初始化事务并手动提交。

public void addUser(User user) {
  try{
    Session session = sessionFactory.getCurrentSession();
    Transaction trans = session.beginTransaction();
    session.save(user);
    trans.commit();
   }catch(Exception e){
     trans.rollback();
   }
}
  

使用spring @Transactional注释自动提交:

由于你正在使用Spring和Hibernate,你不需要手动完成所有这些提交,回滚的东西,就像我上面提到的那样(这是一种做法,但与spring一起使用时并不是一个好习惯)。 Spring为你做到了这一点。您已在spring配置xml中配置了事务管理。现在只需在控制器或服务方法上使用@Transactional注释,您可以在其中调用DAO类进行数据库操作。

@Transactional
public xx xx(){ //Your userService method that calls DAO method
..
}

注意:@Transactional注释应为spring(org.springframework.transaction.annotation.Transactional)。请勿在此处使用javax.transaction