java.lang.ClassCastException: java.lang.Long 无法转换为 [Ljava.lang.Long;遍历数据库中的值

java.lang.ClassCastException: java.lang.Long cannot be cast to [Ljava.lang.Long; on iterating through values from the db

我正在尝试使用休眠获取 table 中的最后数据,如以下代码片段所示

query.setMaxResults(1);
         List<Long[]> rows =  query.list();
         System.out.println("current row>>>>>>  " +rows.toString());

          for (Long[] row: rows) {
                System.out.println(" ------------------- ");
                long val = (Long) row[6];
                System.out.println("current file: " + val);
            }

          }catch(Exception ex){
              ex.printStackTrace();
          }

这是我的查询

Query query = session.createQuery("select f.currentfile.id from File f order by f.id DESC");

我在这行代码中遇到错误

java.lang.ClassCastException: java.lang.Long cannot be cast to [Ljava.lang.Long;
for (Long[] row: rows) {

请问有什么问题吗?

您的查询 returns List<Long> 并且您正在分配 List<Long[]>

Long is java.lang.Long

Long[] is [Ljava.lang.Long

移除query.setMaxResults(1);

否则你会得到一个结果

试试这个

已编辑

     List<Long> rows =  query.list();
     System.out.println("current row>>>>>>  " +rows.toString());

      for (Long val: rows) {
            System.out.println(" ------------------- ");
            System.out.println("current file: " + val);
      }