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

时间:2015-01-06 15:29:13

标签: hibernate spring-mvc

我正在开发一个Spring-MVC应用程序,我在其中使用Hibernate作为ORM工具。我正在为应用程序添加聊天功能,当我尝试添加聊天消息时,我收到 Hibernate的No session error 。我在网上检查了各种解决方案,他们建议使用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";
    }
}

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

1 个答案:

答案 0 :(得分:1)

通过在方法上添加@Transactional,spring将负责创建/关闭hibernate会话并创建/提交/回滚事务。
因此在&#34; addMessage()&#34;中删除此代码方法

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

并在&#34; listMessagesForUser()&#34;中删除此行方法

session = this.sessionFactory.openSession();

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

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