在下面的场景中,我得到了 Shop.events Collection 的LazyInitializationException 。
我知道问题可能在执行 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();