Getting column names from a JPA Native Query

前端 未结 7 1125
孤街浪徒
孤街浪徒 2021-01-02 00:33

I have an administrative console in my web application that allows an admin to perform a custom SQL SELECT query on our database.

Underneath, the application is usin

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 01:24

    2020

    With hibernate 5.2.11.Final is actually pretty easy. In my example you can see how I get the column names for every row. And how I get values by column name.

    Query q = em.createNativeQuery("SELECT columnA, columnB FROM table");
    List result = q.getResultList();
    
    for (Tuple row: result){
    
        // Get Column Names
        List> elements = row.getElements();
        for (TupleElement element : elements ) {
            System.out.println(element.getAlias());
        }
    
        // Get Objects by Column Name
        Object columnA;
        Object columnB;
        try {
            columnA = row.get("columnA");
            columnB= row.get("columnB");
        } catch (IllegalArgumentException e) {
            System.out.println("A column was not found");
        }
    }
    
        

    提交回复
    热议问题