Spring,Hibernate,事务管理,未提交

时间:2012-05-16 15:04:00

标签: java spring hibernate transactions

所以,我尝试使用Spring进行事务管理。最后我的应用程序工作,但删除不提交。在使用Spring之前我在DAO中管理了事务,我想在删除此代码之后。但现在删除不承诺DB。

我的道:

protected Session getSession() {
    Session session = sessionFactory.openSession();
    ThreadLocalSessionContext.bind(session);
    return session;
}
public void delete(T t) {
    Session session = getSession();
// **this approach I used before**
//  session.beginTransaction();
//  try {
//  session.delete(t);
//  session.getTransaction().commit();
//  } catch (Exception e) {
//      session.getTransaction().rollback();
//  }
    session.delete(t);
    }

我的applicationContext:

<?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:tx="http://www.springframework.org/schema/tx"
    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/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://ngs-java-srv.synapse.com:3306/mybase" />
        <property name="username" value="user" />
        <property name="password" value="password" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- <property name="configLocation" value="hibernate.cfg.xml" /> -->

        <property name="packagesToScan" value="todolist.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <!-- dao beans -->
    <bean id="userDao"
        class="todolist.dao.hibernate.UserDaoImpl">
        <constructor-arg>
            <value>todolist.entity.User</value>
        </constructor-arg>
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="itemDao"
        class="todolist.dao.hibernate.ItemDaoImpl">
        <constructor-arg>
            <value>todolist.entity.Item</value>
        </constructor-arg>
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- service bean -->
    <bean id="userService" class="todolist.service.UserServiceImpl">
        <property name="userDao" ref="userDao" />
        <property name="itemDao" ref="itemDao" />
    </bean>

    <!-- transaction manager -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

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

    <!-- <tx:annotation-driven/> -->

<!--    <aop:config>
        <aop:pointcut id="serviceMethods"
            expression="execution(* todolist.service.UserService.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRES_NEW" />
            <tx:method name="deleteItem" no-rollback-for="Exception" />
        </tx:attributes>
    </tx:advice> -->

    <!-- backbeans -->
    <bean id="userLogin" class="todolist.jsf.UserLogin"
        scope="request">
        <property name="userService" ref="userService" />
    </bean>

    <bean id="userLogged" class="todolist.jsf.UserLogged"
        scope="session">
        <aop:scoped-proxy />
    </bean>

    <bean id="userRegister" class="todolist.jsf.UserRegister"
        scope="request">
        <property name="userService" ref="userService" />
    </bean>

    <bean id="createItem" class="todolist.jsf.CreateItem"
        scope="request">
        <property name="userService" ref="userService" />
    </bean>

    <bean id="todoList" class="todolist.jsf.TodoList"
        scope="request">
        <property name="userService" ref="userService" />
    </bean>

</beans>

UserServiceImpl类

package todolist.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import todolist.exception.AuthorizationError;
import todolist.exception.DuplicateLoginsException;
import todolist.service.StringToHashTool;
import todolist.dao.ItemDao;
import todolist.dao.UserDao;
import todolist.entity.Item;
import todolist.entity.User;

public class UserServiceImpl implements UserService {

    //private static final Logger log = Logger.getLogger(UserServiceImpl.class);

    private UserDao userDao;
    private ItemDao itemDao;

    public void setItemDao(ItemDao itemDao) {
    this.itemDao = itemDao;
    }

    public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean isUserExists(String login) {
    return (userDao.getUserByLogin(login) != null);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean isPasswordCorrect(String login, String password) {
    if (isUserExists(login)) {
        return userDao.getUserByLogin(login).getPassword()
            .equals(StringToHashTool.getHash(password));
    } else {
        return false;
    }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public User login(String login, String password) {
    if (isPasswordCorrect(login, password)) {
        return userDao.getUserByLogin(login);
    } else {
        throw new AuthorizationError("Incorrect password");
    }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean register(String login, String password) {
    if (isUserExists(login)) {
        throw new DuplicateLoginsException("Login " + login + " is already used.");
    } else {
        User user = new User();
        user.setLogin(login);
        user.setPassword(StringToHashTool.getHash(password));
        userDao.save(user);
        return true;
    }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void logout() {

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Item createItem(Long creator_id, Long performer_id,
        String description, Date dueDate) {

    Item item = new Item();
    User user = userDao.getById(creator_id);

    item.setCreator(user);

    user = userDao.getById(performer_id);

    item.setPerformer(user);
    item.setDescription(description);
    item.setStartDate(new Date());
    item.setDueDate(dueDate);

    itemDao.save(item);

    return item;
    }

    @Override    
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void deleteItem(Long item_id) {
    Item item = itemDao.getById(item_id);
    itemDao.delete(item);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<Item> getUserItems(String login) {
    User user = userDao.getUserByLogin(login);
    return itemDao.getItemsByPerformer(user.getId());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<User> getUsers() {
    return userDao.getUsers();
    }
}

3 个答案:

答案 0 :(得分:2)

<aop:pointcut 
    id="serviceMethods"
    expression="execution(*todolist.service.UserService.*(..))" 
/>

第一步:

将其更改为:

<aop:pointcut 
    id="serviceMethods"
    expression="todolist.service.UserServiceImpl.delete()" 
/>

查看删除的开始提交。我只是想确保你清除任何错别字以及你有什么。如果此显式配置失败,则配置必定存在问题。

答案 1 :(得分:0)

在DAO中使用getCurrentSession代替openSession,以便getSession方法如下所示:

protected Session getSession() {
    return sessionFactory.getCurrentSession();
}

您正在创建一个使用不同数据库连接的新会话,因此为该服务设置的事务不适用。

同样,在配置DAO时,DAO的默认范围为单例;将实体作为构造函数参数传递没有意义。单例不应具有特定于某个单独事务的实例状态。

答案 2 :(得分:0)

我使用Spring HibernateTransactionManager对象和注释驱动配置取得了成功。在我的应用程序上下文中,我只是声明了以下两个bean:

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="session_factory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

然后在我的服务层中,您的UserServiceImpl例如:

public class UserServiceImpl implements UserService {

private final UserDao userDao;
private final ItemDao itemDao;

public UserServiceImpl(UserDao userDao, ItemDao itemDao) {
    this.userDao = userDao;
    this.itemDao = itemDao;
}

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public boolean isUserExists(String login) {
    return (userDao.getUserByLogin(login) != null);
}

...

将事务注释尽可能靠近视图(在MVC中)移动非常重要。原因是1)性能和2)原子事务。如果调用UserService的调用在单个函数调用中调用isUserExists,isPasswordCorrect和login方法,则您希望这些调用在单个事务中执行。为此,请从UserServiceImpl中删除@Transactional注释并将其移动到调用类。这可确保将单个事务用于所有三个方法调用。对于原子执行,这也有效。想想经典的银行汇款示例。如果在UserService上有两个单独的事务,则前两个方法调用可以成功,最后一个失败。将提交第二个事务,因为它们位于单独的事务块中,这会使数据库处于不一致状态。当然,原子事务主要与写入数据的事务相关。

此外,不要将事务注释添加到接口,将它们保留在实现上。

然后在我的DAO中,我只是做一个sessionFactory.getCurrentSession()并从那里开始。 getCurrentSession()是线程安全的,但保持对DAO是私有的。