当尝试放置从我通过休眠从数据库加载的对象中获取的字符串列表时,我遇到了这个异常。
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
我用来加载列表的方法是在事务中。但是当我尝试将列表放入模型中时,我得到了上述异常。我从中得到了休眠要求我在事务中也有这行代码。但是鉴于它不是数据库操作,为什么会这样呢?
@RequestMapping(value="{id}", method=RequestMethod.POST)
public String addComment(@PathVariable String id, Model model, String comment) {
personService.addComment(Long.parseLong(id), comment);
Person person = personService.getPersonById(Long.parseLong(id));
model.addAttribute(person);
List<String> comments = personService.getComments(id);
model.addAttribute(comments);
return "/Review";
}
服务对象。
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class PersonServiceImpl implements PersonService {
private Workaround personDAO;
public PersonServiceImpl() {
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void savePerson(Person person) {
personDAO.savePerson(person);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public Person getPersonById(long id) {
return personDAO.getPersonById(id);
}
@Autowired
public void setPersonDAO(Workaround personDAO) {
this.personDAO = personDAO;
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public List<Person> getAllPeople() {
return personDAO.getAllPeople();
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void addComment(Long id, String comment) {
Person person = getPersonById(id);
person.addComment(comment);
savePerson(person);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public List<String> getComments(String id) {
return personDAO.getComments(Long.parseLong(id));
}
}
道
import java.util.List;
import javax.persistence.ElementCollection;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class PersonDAO implements Workaround {
private SessionFactory sessionFactory;
@Autowired
public PersonDAO(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
public void addPerson(Person person) {
currentSession().save(person);
}
public Person getPersonById(long id) {
return (Person) currentSession().get(Person.class, id);
}
public void savePerson(Person person) {
currentSession().save(person);
}
public List<Person> getAllPeople() {
List<Person> people = currentSession().createQuery("from Person").list();
return people;
}
public List<String> getComments(long id) {
return getPersonById(id).getComments();
}
}