John Smith
John Smith

Reputation: 69

How to return only one column in Hibernate?

I want to return only one column from table. This is my DAO:

@SuppressWarnings("unchecked")
    public String getUri() {

        return sessionFactory.getCurrentSession()
                .createQuery("uri from Templates WHERE state=1").toString();
    }

Uri is a column. Domain:

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

Console says:

 Request processing failed; nested exception is java.lang.IllegalArgumentException: node to traverse cannot be null!

The second version:

@SuppressWarnings("unchecked")
    public String getUri() {

        return (String) sessionFactory.getCurrentSession()
                .createQuery("select uri from TEMPLATES WHERE state=1")
                .uniqueResult();
    }

Console:

Request processing failed; nested exception is org.hibernate.hql.ast.QuerySyntaxException: TEMPLATES is not mapped [select uri from TEMPLATES WHERE state=1]

Upvotes: 0

Views: 5861

Answers (3)

Wirus
Wirus

Reputation: 1190

As you added select, then call list method on your Query. And get first result from the list if you want to get only first one.

Upvotes: 0

Amin Abu-Taleb
Amin Abu-Taleb

Reputation: 4511

Your SELECT clause is missing:

@SuppressWarnings("unchecked")
    public String getUri() {

        Query q = sessionFactory.getCurrentSession()
                .createQuery("SELECT uri FROM Templates WHERE state=1");

        List l = q.list();

        //guess you know there's only one result?
        return l.get(0).toString();
    }

More info in: https://forum.hibernate.org/viewtopic.php?p=2448422

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120318

You need to use the class/field names, not the table/column names. Also, the query won't return a list of instances of your class for that table, but rather an array. Also, put a select in your query. I believe that exception means your hql is broken.

Upvotes: 0

Related Questions