使用_sessionFactory.getCurrentSession()检索用户会话中的当前用户ID;冬眠

时间:2016-07-26 18:29:06

标签: java spring hibernate spring-boot

我正在尝试编写hql查询以使用此方法检索用户的当前会话

@Autowired
    private SessionFactory _sessionFactory;

    private Session getSession() {
        return _sessionFactory.getCurrentSession();
    }

我正在努力实现这样的目标

return getSession().createQuery("SELECT  FROM Users u WHERE u.id = :userIdFromSession AND u.isAdmin = true").list();

这是我的方法

return getSession().createQuery("SELECT  FROM Users u WHERE u.id = " +:getSession() +"AND u.isAdmin = true").list();

假设getter和setter到位,这是用户实体类

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "userId")
    private Long id;
    @Column(nullable = false)
    private String name;
    @Column(unique = true, nullable = false)
    private String email;
    @Column(nullable = false)
    private long timestamp;

    @OneToOne
    @JoinColumn(name = "adminId",nullable = false)
    Admin admin;

    @Column(nullable = true)
    private boolean isAdmin;

假设有getter和setter,这是聊天实体类

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "chatId")
    private Long id;
    private String message;

    @OneToOne
    @JoinColumn(name = "userId")
    User user;

现在你可以看到聊天引用用户了。你必须是一个用户才能聊天,所以我想在dao类中以这种方式检索用户的聊天

// return getSession().createQuery("SELECT  FROM Chats u WHERE u.id = :userIdFromSession AND u.isAdmin = true").list();

这是我用来在我的控制器类中创建用户的方法

@RequestMapping(value = "/create-user", method = RequestMethod.POST)
    public ModelAndView createUser(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @RequestParam String name,
                                   @RequestParam String email) {
        try {
            // create new user object
            User user = new User();
            user.setName(name);
            user.setEmail(email);
            user.setTimestamp(new Date().getTime());

            // save user in db (if new)
            if (_userDao.getByEmail(email) == null) {
                _userDao.save(user);
            }

            // save in cookie
            Cookie cookie = new Cookie("name", name);
            Cookie cookie1 = new Cookie("email", email);
            response.addCookie(cookie);
            response.addCookie(cookie1);
        } catch (Exception e) {
             e.printStackTrace();
            //logger.error("Exception in creating user: ", e.getStackTrace());
        }

        return new ModelAndView("redirect:/");
    }

这种方法不仅仅是因为它抛出编译错误。 请帮助!

1 个答案:

答案 0 :(得分:1)

Hibernate Session与用户的会话无关。您可以根据与数据库的连接来考虑它。

SessionFactory#getCurrentSession()返回当前会话(如果已经打开)。通过它,您可以查询数据库。

我现在理解你的问题的方法是识别将处理身份验证的Spring MVC控制器。你的createUser()方法可能就是其中之一,但你肯定还需要一个authenticateUser()。假设电子邮件是唯一的,您可以使用该电子邮件作为登录来验证用户身份。假设您的getByEmail方法返回用户POJO。我会留下异常处理和Spring MVC的东西。

public ModelAndView authenficateUser(HttpServletRequest request,
                               HttpServletResponse response,
                               @RequestParam String email) {
    User u = _userDao.getByEmail(email);
    if (u == null) {
        // deal with unknown user and return to login form
    } else {
        request.getSession().setAttribute("email", email);
        // success
    }
}

然后你应该在控制器的某个地方有一个getChats方法。

public ModelAndView getChats(HttpServletRequest request,
                               HttpServletResponse response) {
    String email = (String) request.getSession().getAttribute("email");        
    if (email == null) {
        // user is not logged in, deal with it.
    } else {
        List<Chat> chats = _chatDao.getChats(email);
        return new ModelAndView("chatView", "chats", chats);
    }
}

在ChatDao中,你有一个这样的方法:

List<Chat> getChats(String email) {
    String hql = "from Chat c where c.user.email = :email";
    _sessionFactory.getCurrentSession().createQuery(hql).setParameter("email", email).list();
}