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

安德里亚·罗宾逊(Andrea Robinson)

我正在尝试编写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();

假设获取器和设置器到位,这是用户实体类

@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:/");
    }

这种方法不仅会抛出编译错误,而且还无法解决问题。请协助!

亚瑟·诺塞达(Arthur Noseda)

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();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Hibernate中使用SessionFactory.getCurrentSession()时获取Connection对象

如何从 ci_sessions 中检索当前用户会话 ID。?

使用android中的SQLite检索当前登录用户的用户名

如何使用C#获取.NET中的当前用户名?

张量流c ++代码SessionFactory :: GetFactory如何选择要使用的会话?直接还是Grpc会话?

如何使用用户ID在Firebase中检索字段

如何使用身份获取ApplicationDbContext中当前登录的用户ID?

如何使用flask在python中检索每个用户的会话存储中存储的相应数据集?

使用SQL检索Sparx EA中的当前选定对象

使用cURL检索TeamCity中的当前构建状态

Web服务中的NHibernate“在创建SessionFactory时使用了无效或不完整的配置”

使用会话和LINQ从用户的工作中获取用户的个人资料ID

如何在rails.yml中创建if语句以基于Rails中的当前用户使用不同的数据库

如何使用ID销毁特定用户的会话?

从 Spring 的当前会话中获取用户信息?

使用MeteorJS堆栈,如何从用户发布的帖子中检索带有用户ID的用户电子邮件

使用当前用户ID-Symfony 2

从LookBack使用用户ID检索用户名

使用 Django 信号识别当前用户会话

休眠:sessionFactory.openSession()VS sessionFactory.getCurrentSession()

Hibernate的Sessionfactory.getCurrentSession()和SessionFactory.openSession()的区别

使用SwiftUI和MapKit检索用户当前位置

班级中的当前用户

使用hibernate sessionFactory还是JPAEntityManager?

使用spring的sessionFactory出现NullPointerException

从WooCommerce中的当前用户订单获取订单ID

如何获取CloudKit中的当前用户ID?

如何使用ember-simple-auth在会话中存储用户ID?

使用会话数据用户 ID 进行的条件检查在 codeigniter 中不起作用