数据未存储在数据库中

时间:2011-10-14 11:15:47

标签: java hibernate spring

我在netbeans中实现了spring和hibernate注释。当我尝试将数据保存在数据库中时,它不会发生。当我从netbeans启动应用程序但未能在其中存储数据时,将创建表。

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
    <property name="url" value="jdbc:derby://localhost:1527/seed"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.vaannila.domain.User</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

dao class:

@Repository("userDao")
public class UserDAOImpl implements UserDAO {

@Autowired
private SessionFactory sessionFactory;

/*public void setSessionFactory(SessionFactory sessionFactory) {
    this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}*/

@Override
public void saveUser(User user) {
    sessionFactory.getCurrentSession().saveOrUpdate (user);
}

@Override
@SuppressWarnings("unchecked")
public List<User> listUser() {
    return (List<User>) sessionFactory.getCurrentSession().
                    createCriteria ( User.class ).list(); 
}

}

服务类:

@Service("userService")
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class UserServiceImpl implements UserService {

    @Autowired
private UserDAO userDAO;

    @Override
public void saveUser(User user) {
    userDAO.saveUser(user);
}

@Override
@SuppressWarnings("unchecked")
public List<User> listUser() {
    return userDAO.listUser();
}

}

请帮帮我。

提前致谢

1 个答案:

答案 0 :(得分:4)

问题是您使用的交易在服务中被标记为回滚(readOnly)!

因此,您需要将@Transaction(readOnly=false)添加到您的控制器或服务方法或dao,以触发项目的商店操作。

例如:

@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class UserServiceImpl implements UserService {

    ...

    //Do not role back this transaction
    @Transactional(propagation=Propagation.SUPPORTS, readOnly=false)
    @Override
    public void saveUser(User user) {
       userDAO.saveUser(user);
    }
}

@See Spring Reference: Chapter 10.5.6 Using @Transactional形成一些细节