在Spring 3和Hibernate 4中保持长时间的事务会话

时间:2013-08-19 19:38:30

标签: spring hibernate session transactions

我在下面的场景中得到 LazyInitializationException 到Shop.events集合。

我知道问题可能会在调用shop.getEvents之前关闭事务会话。

我正在学习OpenSessionInViewFilter,但我认为在服务器的每个调用生命周期中保留每个事务会话并不是一个好主意。并且FetchType.EAGER也不好。

我需要帮助来解决这个问题。提前谢谢。

@Entity
@Table(name = "shop")
public class Shop implements Serializable {

    // Another class attributes.    

    @OneToMany(mappedBy = "shop", fetch=FetchType.LAZY)
    private Set<Event> events;

    // Getters and setters.

}

@Entity
@Table(name = "event")
public class Event implements Serializable {

    // Another class attributes.

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "shop_id", nullable = false)
    private Shop shop;

    // Getters and setters.

}

持久层实施。

public interface AbstractDao<E, I extends Serializable> {

    E findUniqueByCriteria(Criteria criteria);

}

public interface ShopDao extends AbstractDao<Shop, String>{

    Shop getShopFromId(int shop_id, int manager_id);

}

@Repository("shopDao")
public class ShopDaoImpl extends AbstractDaoImpl<Shop, String> implements ShopDao {

    protected ShopDaoImpl() {

        super(Shop.class);
    }

    @Override
    public Shop getShopFromId(int shop_id, int manager_id) {

        Criteria criteria = this.getCurrentSession().createCriteria(Shop.class)
                .add(Restrictions.and(
                Restrictions.like("active", true),
                Restrictions.like("id", shop_id)))
                .createCriteria("manager").add(
                Restrictions.like("id", manager_id));

        return (Shop) this.findUniqueByCriteria(criteria);
    }

}

public interface ShopService {

    Shop getShopFromId(int shop_id, int manager_id);

}

@Service("shopService")
@Transactional(readOnly = true)
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopDao shopDao;

    @Override
    public Shop getShopFromId(int shop_id, int manager_id) {

        return this.shopDao.getShopFromId(shop_id, manager_id);
    }

}

控制器看起来像这样。

类属性。

@Autowired
private ShopService shopService;

方法控制器。

Manager manager = (Manager) request.getSession(false).getAttribute("manager");

Shop shop = (Shop) this.shopService.getShopFromId(shop_id, manager.getId());

Set<Event> events = shop.getEvents();

1 个答案:

答案 0 :(得分:0)

解决方案是使用@Transactional(propagation = Propagation.REQUIRED)配置Controller方法。因此在方法持久化操作中使用相同的事务会话。