【问题标题】:Get entity by email in hibernate在休眠中通过电子邮件获取实体
【发布时间】:2017-04-30 14:32:18
【问题描述】:

我正在尝试从他的电子邮件中获取用户,该电子邮件在数据库中是唯一的。

我写了这段代码:

session.beginTransaction();
User user =  (User) session.createQuery("select * from `user`  where email = '"+email+"'");
session.getTransaction().commit();

这段代码对吗?或者休眠中有一些函数可以按列值获取实体?

【问题讨论】:

  • 创建查询应该是您要查找的内容,除非电子邮件是 ID,否则您可以使用 get。但请注意,出于安全原因,您不应简单地将电子邮件放入字符串中。您应该使用参数,如下所述:stackoverflow.com/questions/4340346/…
  • 不,这是不对的。 createQuery 需要一个 JPQL 查询。而且你通过的不是JPQL。学习 JPQL:docs.jboss.org/hibernate/orm/current/userguide/html_single/…。还要学习使用查询参数而不是串联,因为您的代码容易受到 SQL/JPQL 注入攻击。最后,如文档所述,createQuery 返回的是查询,而不是用户。您需要使用 getResultList() 或 getSingleResult() 执行该查询。
  • 确实我没有注意到查询的具体写法,但createQuery 仍然是这里使用的方法。

标签: java mysql hibernate


【解决方案1】:

我发现您当前的代码存在两个问题。首先,您似乎正在运行本机 SQL 查询,而不是 HQL(或 JPQL)。其次,您的查询是使用字符串连接构建的,容易受到 SQL 注入的攻击

考虑以下代码:

Query query = session.createQuery("from User u where u.email = :email ");
query.setParameter("email", email);
List list = query.list();

【讨论】:

  • 事务不仅仅用于原子性。隔离也很重要。在查询返回后能够导航到实体图也很重要。交易总是一个好主意。此外,它应该是select u from User u...,带有大写 U,因为那是类名。
  • @JBNizet 当我写到我在考虑 JDBC 时,在这种情况下,我们可能不会将显式事务用于简单的选择,而是用于更新等我们希望选项执行的地方回滚。是的,Hibernate 中数据库的每一次点击都可能背后有一个事务。 OP 省略了这段代码(以及其他一些东西)。
  • 感谢您的回答,但似乎在休眠中不推荐使用“查询”类
  • 再次感谢@TimBiegeleisen
【解决方案2】:

无需编写任何 SQL:

  public static Person getPersonByEmail(String email)  {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        CriteriaBuilder cb = session.getCriteriaBuilder();

        CriteriaQuery<Person> cr = cb.createQuery(Person.class);
        Root<Person> root = cr.from(Person.class);
        cr.select(root).where(cb.equal(root.get("email"), email));  //here you pass a class field, not a table column (in this example they are called the same)

        Query<Person> query = session.createQuery(cr);
        query.setMaxResults(1);
        List<Person> result = query.getResultList();
        session.close();

        return result.get(0);
  }

使用示例:

public static void main(String[] args)  {
  Person person = getPersonByEmail("test@mail.com");
  System.out.println(person.getEmail());  //test@mail.com
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 2019-05-29
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多