Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query using alias on column give an error

When i use alias for column i get error. Without alias everytinig works good. What is the problem with that ? This is simple example, but need to use more aliases in real project to wrap results in some not-entity class, but can't because of this error. How to solve this ?

NOT WORKING (with alias on id column):

public List<Long> findAll(Long ownerId) {
    String sql = "select id as myId  from products where ownerId = "+ownerId;
    SQLQuery query = getSession().createSQLQuery(sql);
    return query.list();
}

Error:

WARN [JDBCExceptionReporter:77] : SQL Error: 0, SQLState: S0022 ERROR [JDBCExceptionReporter:78] : Column 'id' not found.

WORKING (without alias):

public List<Long> findAll(Long ownerId) {
    String sql = "select id from products where ownerId = "+ownerId;
    SQLQuery query = getSession().createSQLQuery(sql);
    return query.list();
}
like image 645
marioosh Avatar asked Aug 19 '11 08:08

marioosh


1 Answers

If your "product" is mapped, hibernate probably don't know about "myId" and therefore can't select it. You can try something like:

getSession().createSQLQuery(sql).addScalar("myId", Hibernate.LONG)
like image 192
Dainius Avatar answered Nov 15 '22 21:11

Dainius