Java Hibernate 5.2 版本 -> 很多查询方法被弃用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38460764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:21:01  来源:igfitidea点击:

Hibernate 5.2 version -> A lot of Query methods deprecate?

javasqlhibernatehqldao

提问by Chenya Zhang

I'm new to Hibernate.

我是 Hibernate 的新手。

I'm trying to get a list of first name and last name of all administrators.

我正在尝试获取所有管理员的名字和姓氏的列表。

There are two warnings in my following code. I already tried to search a lot online.

我的以下代码中有两个警告。我已经尝试在网上搜索了很多。

1) Query is a raw type. References to generic type Query should be parameterized.

1) Query 是原始类型。对泛型类型 Query 的引用应该被参数化。

2) The method list() from the type Query is deprecated.

2) 不推荐使用 Query 类型的方法 list()。

public List<Object> loadAllAdmins() {
                List<Object> allAdmins = new ArrayList<Object>();
                try {
                        HibernateUtil.beginTransaction();

                        Query q = currentSession.createQuery("SELECT admin.firstName, admin.lastName from AdminBean admin");

                        allAdmins= q.list();

                        HibernateUtil.commitTransaction();
                } catch (HibernateException ex) {
                        System.out.println("List<AdminBean> loadAllPersons: HibernateException");
                }
                return allAdmins;
        }

But I see sample code like this all over the web. How should I solve these two problems?

但是我在整个网络上都看到了这样的示例代码。我该如何解决这两个问题?

Update

更新

I just tried to use Criteria as suggested. It also says the list() method is deprecate for Criteria... It seems that a lot of methods are deprecate for both Query and Criteria, including uniqueResult() and others... Any suggestion how I should replace them?

我只是尝试按照建议使用 Criteria。它还说 list() 方法不推荐用于 Criteria ......似乎很多方法都被 Query 和 Criteria 弃用,包括 uniqueResult() 和其他......我应该如何替换它们的任何建议?

采纳答案by Pika

public List<Admin> getAdmins() {
    List<Admin> AdminList = new ArrayList<Admin>(); 
    Session session = factory.openSession();
    for (Object oneObject : session.createQuery("FROM Admin").getResultList()) {
        AdminList.add((Admin)oneObject);
    }
    session.close();
    return AdminList;
}

The warnings came from "Type Inference".

警告来自“类型推断”。

I had the similar problem. However, I found a solution without "SuppressWarnings".

我有类似的问题。但是,我找到了一个没有“SuppressWarnings”的解决方案。



Recently, I found out a shorter way to code the same things without type inference.

最近,我发现了一种无需类型推断即可对相同内容进行编码的更短方法。

public List<Admin> getAdmins() {
    Session session = factory.openSession();
    TypedQuery<Admin> query = session.createQuery("FROM Admin");
    List<Admin> result = query.getResultList();
    session.close();
    return result;
}

Hope it helps.

希望能帮助到你。

回答by A. Horst

Did you try use criteria?

您是否尝试使用标准?

See that example:

看那个例子:

public List<NoteVO> listNotes() {
    Session session = HibernateSessionFactory.getSession();

    Criteria crit = session.createCriteria(NoteVO.class);

    List<NoteVO> listNotes = crit.list();

    session.close();
    return listNotes;
}

回答by Johannes H

I tested other methods of hibernate javadocand i came up with getResultList()method of the TypedQuery<T>interface. Example:

我测试了hibernate javadoc 的其他方法,我想出了接口的getResultList()方法TypedQuery<T>。例子:

public List<Admin> getAdmins() {
  Session session = factory.openSession();
  @SuppressWarnings("unchecked")
  List<Admin> result = session.createQuery("FROM Admin").getResultList();
  session.close();
  return result;
}

The difference is that the returned type of createQueryis not Querybut a subinterface called TypedQuery<T>. Because it is typed, it also fixes the "Query is a raw type" warning.

不同之处在于返回的类型createQuery不是Query一个名为 的子接口TypedQuery<T>。因为它是typed,它还修复了“查询是原始类型”警告。

With this solution you may get a Type Safetywarning, which can be solved by either casting each object explicitly or by adding @SuppressWarnings("unchecked")

使用此解决方案,您可能会收到类型安全警告,可以通过显式转换每个对象或添加@SuppressWarnings("unchecked")

Regarding criterias see hibernate user guide

关于标准,请参阅hibernate 用户指南

Nevertheless, i am wondering why the tutorials-page of hibernate is not adjusted.

尽管如此,我想知道为什么不调整 hibernate 的教程页面。

回答by Aniket Warey

Don't import QUERYfrom org.hibernate(As its Deprecated now). Instead import from “org.hibernate.query” .Eclipse reference

不要QUERYorg.hibernate(现在已弃用)导入。而是从“org.hibernate.query”导入。日食参考

回答by Menai Ala Eddine

According to Hibernate Create Query, there are two types of createQuery()methods :

根据Hibernate Create Query,有两种类型的createQuery()方法:

Query createQuery(java.lang.String queryString )
Query createQuery(java.lang.String queryString )

Create a Query instance for the given HQL/JPQL query string.

为给定的 HQL/JPQL 查询字符串创建一个 Query 实例。

<R> Query<R> createQuery(java.lang.String queryString,
                         java.lang.Class<R> resultClass)
<R> Query<R> createQuery(java.lang.String queryString,
                         java.lang.Class<R> resultClass)

Create a typed Query instance for the given HQL/JPQL query string.

为给定的 HQL/JPQL 查询字符串创建一个类型化的 Query 实例。

In your case you used the first Queryand list() method is @deperecated.

在您的情况下,您使用的第一个Query和 list() 方法是@deperecated.

You can user getResultList()instead of list()for Multiple results :

您可以使用用户getResultList()代替list()多个结果:

List<Object> loadAllAdmins() {
    List<Object> allAdmins = new ArrayList<Object>();
        try {
       HibernateUtil.beginTransaction();

       allAdmins= List<Object> currentSession.createQuery("SELECT admin.firstName, admin.lastName from AdminBean admin").getResultList();


                        HibernateUtil.commitTransaction();
                } catch (HibernateException ex) {
                        System.out.println("List<AdminBean> loadAllPersons: HibernateException");
                }
                return allAdmins;
        }

For single result you can use getSingleResult():

对于单个结果,您可以使用getSingleResult()

       Admin= (Object) currentSession.createQuery("SELECT admin.firstName, admin.lastName from AdminBean admin").getSingleResult();

PS:I used Objectbased on your type Object,you can cast the result according to used type.

PS:我是Object根据你的类型使用的Object,你可以根据使用的类型来转换结果。

回答by sharmaap

Although late to the party but may be worth noting the overloaded createQuery method (to avoid warnings altogether):

虽然晚了,但可能值得注意的是重载的 createQuery 方法(完全避免警告):

public List<Admin> loadAllAdmins() {
    try {
        HibernateUtil.beginTransaction();
        List<Admin> admins = currentSession.createQuery("SELECT admin.firstName, admin.lastName from AdminBean admin", Admin.class).getResultList();
        HibernateUtil.commitTransaction();
        return admins;
    } catch (HibernateException ex) {
        System.out.println("List<AdminBean> loadAllPersons: HibernateException");
        return new ArrayList<>();
    }
}