在下面的场景中,我获得了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();发布于 2013-08-19 21:24:29
解决方案是使用@Transactional(传播= Propagation.REQUIRED)的Controller方法。因此,在方法持久性操作中使用相同的事务会话。
https://stackoverflow.com/questions/18321752
复制相似问题