7

I got this exception when i try to get the list using NamedQuery:

org.hibernate.exception.SQLGrammarException: could not execute query

Below I mentioned code:

Entity Class Code:

@Table(name = "tbl_users")
@XmlRootElement
@NamedQueries({@NamedQuery(name = "TblUsers.findAll", query = "SELECT t FROM TblUsers t")});

DAO implement Code:

org.hibernate.Query query = session.getNamedQuery("TblUsers.findAll");
List list = query.list();

Please provide solution for this exception.

3
  • Have you tried just "from TblUsers t"? This is the correct HQL syntax. Commented Aug 1, 2011 at 14:10
  • @Olaf - "select t from TblUsers t" is correct HQL as well Commented Aug 1, 2011 at 17:06
  • You need to show the whole stack trace. SQLGrammarException means SQL (as translated by Hibernate) was not accepted by your database. Make sure that the table exists (in proper schema). Commented Aug 1, 2011 at 17:08

5 Answers 5

11

Was facing same issue for a while and figured out that the problem was due to the Table name being different from the class(or Entity) name in the database. Added the @Table(name = actual_table_name) annotation and it worked.

Sign up to request clarification or add additional context in comments.

Comments

5

Get the SQL query that Hibernate is generating (using hibernate.show_sql or, preferably, Hibernate's SQL logging), and execute it against the database yourself. That will most likely help steer you in the right direction.

1 Comment

I've tried using hibernate.show_sql but all I get is insert into table (column) values (?) How can we actually see the REAL SQL and not just a bunch of ? marks?
1

Try this one it could work. It Perfectly worked for me.

1) Class level annotation.

@NamedQuery(name="UserDetails.byId" , query="from UserDetails where userId = ?")

2) Get record using NamedQuery

Query qry2 = sf.getCurrentSession().getNamedQuery("USER_DETAILS.byName")    ;
        qry2.setString(0, "Angad Bansode");
        List<UserDetails> user = qry2.list();
        for (UserDetails userDetails : user) {
            System.out.println("User Details by named native query  name = " + userDetails.getUserName() + ", aadhaar no  = " + userDetails.getAadharNo());
        }

Comments

0

seems like this question is little old but any way once i added below line to hibernate config files it worked for me.

<property name="show_sql">true</property>

Comments

0

For me it was missing access to sequence for auto-increment primary key. After adding this error was resolved.

GRANT USAGE, SELECT ON ALL
    SEQUENCES IN SCHEMA public
    TO "${user-name}";;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.