Java 休眠:如何选择表中的所有行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31583737/
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 11:16:32  来源:igfitidea点击:

hibernate: how to select all rows in a table

javamysqlsqlhibernatepostgresql

提问by Ruthi Ruth

I try to do something like Select * from LogEntrywith Hibernate. insert works fine:

我尝试Select * from LogEntry用 Hibernate做一些类似的事情。插入工作正常:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

[...]
protected EntityManager manager;

protected final String tableName = "LogEntry";

public DatabaseImpl(DB_TYPE db) {
    this.db = db;
    if (entityManagerFactory != null && entityManagerFactory.isOpen()) {
        entityManagerFactory.close();
    }
    entityManagerFactory = Persistence.createEntityManagerFactory(db.getPersUnit());
    manager = entityManagerFactory.createEntityManager();
}
public void insert(LogEntry entry) {

    manager.getTransaction().begin();
    manager.persist(entry);
    manager.getTransaction().commit();
}

But when I try to get the inserted values using this method: public LogEntryList getAll() {

但是当我尝试使用此方法获取插入的值时: public LogEntryList getAll() {

    manager.getTransaction().begin();

    Query query = manager.createNativeQuery("SELECT * FROM " + tableName + ";");
    ArrayList<LogEntry> entries = (ArrayList<LogEntry>) query.getResultList();
    manager.getTransaction().commit();

    return new LogEntryList(entries);
}

I always get the Exception: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to de.motza.entities.LogEntry

我总是得到异常: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to de.motza.entities.LogEntry

I know the problem is the casting of the Query result to the object, but I can't find anywhere how to cast the objects properly, or how to get more than one row from the table.

我知道问题是将查询结果转换为对象,但是我找不到任何地方如何正确转换对象,或者如何从表中获取多于一行。

does anybody have any advice? If requested, I can post my persistence.xml and more code

有人有什么建议吗?如果需要,我可以发布我的 persistence.xml 和更多代码

采纳答案by Sunil

Becuase you have used nativeQuery so you need to transfer result by using setResultTransormermethod.

因为你已经使用了 nativeQuery 所以你需要通过 usingsetResultTransormer方法来传输结果。

Query query = manager.createNativeQuery("SELECT * FROM " + tableName + ";");
query.setResultTransformer(Transformers.aliasToBean(LogEntry.class))
ArrayList<LogEntry> entries = (ArrayList<LogEntry>) query.getResultList();

回答by Florian Schaetz

The "problem" is, that you are sending a native query which will return an Object[] array, with one value for each dolumn. You do not need to call a native query, but a hibernate query, for example...

“问题”是,您正在发送一个本机查询,该查询将返回一个 Object[] 数组,每个 dolumn 都有一个值。您不需要调用本机查询,而是调用休眠查询,例如...

manager.createQuery("SELECT l FROM LogEntry");

manager.createQuery("SELECT l FROM LogEntry");

see, for example, this answer.

例如,请参阅此答案

回答by Tim Biegeleisen

For starters, you should try to take advantage of HQL, Hibernate Query Language. In the example you gave above, you are trying to execute a native SQL query. The reason you are getting the ClassCastExceptionis that the native query is circumventing the framework and returning raw Objects instead of the type you want.

对于初学者,您应该尝试利用 HQL,Hibernate 查询语言。在上面给出的示例中,您正在尝试执行本机 SQL 查询。您得到 的原因ClassCastException是本机查询绕过框架并返回 raw Objects 而不是您想要的类型。

Try using this code instead for your SELECT *:

尝试使用此代码代替您的SELECT *

String hql = "from LogEntry";
Session session = entityManagerFactory.openSession();
Query query = session.createQuery(hql);
List<LogEntry> logEntries = query.list();      // no ClassCastException here

回答by Tharkana

As i know getResultList() gives you a List...not a generic List. So if you want to get a generic list you have to use

我知道 getResultList() 给你一个列表......不是一个通用的列表。因此,如果您想获得通用列表,则必须使用

TypedQuery<Person> 

insted of

插入的

Query

This is the link i got the information.

这是我得到信息的链接。

Cast to something the result of Query.getResultList()?

将 Query.getResultList() 的结果转换为某些内容?

I don't know much about Hibernate. i hope this will help you.

我对 Hibernate 了解不多。我希望这能帮到您。

回答by Mahbub

You can use session.createCriteria(MyEntity.class).list();for example.

session.createCriteria(MyEntity.class).list();例如,您可以使用 。

ref: Retrieving all rows of a table without HQL?

ref:在没有 HQL 的情况下检索表的所有行?

回答by Gol.D

List<String> list = null;

TypedQuery<String> query = sessionfactory.openSession().createQuery("from yourTableName");

list = query.getResultList();

yourTableNamecan be your @Entityclass

yourTableName可以成为你的@Entity班级