LazyInitializationException in Spring service
I'm developing an application in Spring 3.0.5 and Hibernate 3.6.2, and currently i'm working in a JSON controller, but i have this exception and i can't understand why is happening. I've checked previously in SO and Google, but this problem is quite strange. So here is my code:
Controller
@RequestMapping(value = "/props", method = RequestMethod.GET)
public @ResponseBody
List<Property> getJsonProps(String id) {
if(id==null)return null;
Device dev = deviceService.getDispositivo(Long.parseLong(id));
List<Property> props = deviceServic开发者_如何学JAVAe.listProperties(dev, 10);
return props;
}
Device Service
@Service("manageDevices")
@Transactional(readOnly=true,propagation=Propagation.REQUIRED)
public class ManageDevicesImpl implements ManageDevices {
private Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private DevicesDAO devicesDAO;
public List<Property> listProperties(Device dev, Integer qty) {
List<Property> props = devicesDAO.pickProperties(dev, qty);
return props;
}
}
DAO
@Repository("devicesDAO")
public class DevicesDAOImpl implements DevicesDAO {
private Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private SessionFactory sessionFactory;
public List<Property> pickProperties(Device dev, Integer qty) {
if(qty >= 0){
log.debug("Open? "+ sessionFactory.getCurrentSession().isOpen());
log.debug("Tx Active? " + sessionFactory.getCurrentSession().getTransaction().isActive());
List<Property> props = dev.getProperties();
if(props != null){
if(props.size() >= qty)
return props.subList(0, qty-1);
else
return props;
}
}
return null;
}
}
The exception occurs in the pickProperties function (DAO Layer), at the line where i try to load the properties (getProperties). In the logs, there is an open session and transaction. Thanks in advance.
Could you post the exact exception you got?
You're in a transaction at the dev.getProperties()
line, but not the transaction where dev
was loaded. You either need to reattach it, or arrange for dev.getProperties()
to be called while you're still in the transaction that loaded it, or move the transactional boundary up so that both calls are in the same transaction, or change the Hibernate configuration so that properties
isn't lazy loaded, or change the code that loads dev
so that it fetches properties
in HQL.
Which of those options will apply to you depends on your situation, but I'd start with the last one.
Looks like your transaction is created after the Device dev
is read. Try reading/rereading it within the transaction to see what happens.
精彩评论