Hibernate 无法初始化代理 - 即使使用 Eager 加载也没有会话

Hibernate could not initialize proxy - no Session even with Eager loading

我正在开发一个 Spring-MVC 应用程序,我在其中使用 Hibernate 作为 ORM 工具。我正在向应用程序添加聊天功能,当我尝试添加聊天消息时,出现 Hibernate 的无会话错误。我在网上查看了各种解决方案,他们建议使用 Eager 方法,但我已经将其作为预加载,但仍然出现错误。我把代码贴出来了,大家看看。

用户模型:

@Entity
@Table(name="userinfo")
public class User implements UserDetails{

// I am using 2 foreign keys in the database to store the sender and receiver id for the message.

    @OneToMany(mappedBy = "user2", fetch = FetchType.EAGER)
    private Set<Messages> messages1 = new HashSet<Messages>();

   @OneToMany(mappedBy = "user3", fetch = FetchType.EAGER)
    private Set<Messages> messages2 = new HashSet<Messages>();
}

消息模型

@Entity
@Table(name = "conversation")
public class Messages {
 @ManyToOne
    @JoinColumn(name = "id")
    private User user2;

    @ManyToOne
    @JoinColumn(name = "userinfo_id")
    private User user3;
}

MessagesDAOImpl :

 @Override
    @Transactional
    public boolean addMessage(User sender, User receiver, Messages messages) {

   @M.Denium : When I remove the below 4 lines, it works. Can you please tell me why? 
          session = this.sessionFactory.getCurrentSession();

 /*  int id = sender.getId();
    int id2 = receiver.getId();
    User sender1 = (User) session.get(User.class,id);
    User receiver1 = (User) session.get(User.class,id2);*/
   /* sender.getMessages1().add(messages);
    receiver.getMessages2().add(messages);*/
    messages.setConversationtimestamp(new Date());
    messages.setUser2(sender);
    messages.setUser3(receiver);
    session.merge(messages);
    session.flush();
    return true;
}
 @Override
    @Transactional
    public List<Messages> listMessagesForUser(User user) {
        session = this.sessionFactory.openSession();
       /* if(session == null){
            session = this.sessionFactory.openSession();
        } else{
            session = this.sessionFactory.getCurrentSession();
        }*/
        int id = user.getId();
        Query query = session.createQuery("from Messages as m where m.user2.id=:id");
        query.setParameter("id",id);
        List<Messages> messagesList= query.list();
        session.flush();
        return messagesList;
    }

MessageController:

@Controller
public class MessageController {

 @RequestMapping(value = "/messages/add/{receiverid}")
    public String sendMessages(@ModelAttribute("messages")Messages messages, @PathVariable("receiverid") int receiverid, Model model){
        User user = userService.getCurrentlyAuthenticatedUser();
        User user1 = userService.getUserById(receiverid);
        this.messageService.addMessage(user,user1,messages);
        model.addAttribute("messages", new Messages());
        model.addAttribute("listMessages", this.messageService.listMessagesForUser(user));
        return "messages";
    }

    @RequestMapping(value = "/messages/list")
    public String listMessages(@ModelAttribute("messages") Messages messages, Model model){
        User user = userService.getCurrentlyAuthenticatedUser();
        model.addAttribute("messages", new Messages());
        model.addAttribute("listMessages", this.messageService.listMessagesForUser(user));
        return "messages";
    }
}

我做错了什么,欢迎任何指点,如果需要更多信息,请告诉我。谢谢你。

通过在您的方法上添加@Transactional,spring 将处理create/close 休眠会话和create/commit/rollback 事务。
所以删除 "addMessage()" 方法中的这段代码

if( session == null) {
    session = this.sessionFactory.openSession();
}else {
    session = this.sessionFactory.getCurrentSession();
}

并在 "listMessagesForUser()" 方法中删除这一行

session = this.sessionFactory.openSession();

而只是使用 "sessionFactory.getCurrentSession()" 获取当前会话并在方法中使用它。 您还需要通过在 @Configuration bean 上添加 @EnableTransactionManagement 来启用事务管理。

您可以阅读有关 spring transaction management 的所有内容。