【问题标题】:Mantain long Transaction Session in Spring3 and Hibernate4在 Spring 3 和 Hibernate4 中保持长事务会话
【发布时间】:2013-08-19 19:38:29
【问题描述】:

在以下场景中,我将 LazyInitializationException 发送到 Shop.events Collection。

我知道问题可能在执行 call 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();

【问题讨论】:

    标签: spring hibernate session transactions


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      相关资源
      最近更新 更多