hql error in select clause - java

When I am using HQL select clause following error is occuring .student is mysql table.
Error:
Hibernate: select studentcla0_.vStudentName as col_0_0_ from student studentcla0_
java.lang.String
Below is Code:
public static void querySubject(Session session)
{
String sql_query="select stud.strStudentName from StudentClass as stud";
Query query1=session.createQuery(sql_query);
for(Iterator it=query1.iterate();it.hasNext();)
{
Object[] row = (Object[]) it.next();
System.out.println("Subject Name:"+row[0]);
}
return;
}

is it hql or sql. If sql try:
session.createSQLQuery(...)

Just to confirm - you have a table in your database called "student" and it has a column called "vStudentName" which is a string type of some sort? The mapping is complete, and has resulted in a translation to this SQL:
select studentcla0_.vStudentName as col_0_0_
from student studentcla0_
Does this run against your database directly, or does it error there as well?

When you select a single value (be it property or entity), Hibernate will return that value directly; it will not be wrapped in an Object array. See details here. So your code should be:
for(Iterator it=query1.iterate(); it.hasNext(); ) {
System.out.println("Subject Name:"+ it.next());
}

Related

how to fetch last column of the selected table using hibernate?

i am trying to fetch the id of last column in descending order.
the query which returns last column is
select id from(select id from challan
order by id desc) where ROWNUM=1;
now i am trying to do same thing using hibernate.
public long getIdOnChallanTable() {
session = sessionFactory.openSession();
trans = session.beginTransaction();
Query<Object[]> query = session.createNativeQuery("select id
from(select id from challan order by id desc) where ROWNUM=1;");
Long value = 0L;
List<Object[]> list = query.getResultList();
for ( Object lst : list){
Object[] objects =(Object[]) lst;
value=(Long)(objects[0]);
}
return value;
}
and the error is:
2017-07-26 12:37:36 [http-nio-7080-exec-1] WARN :: SQL Error: 911, SQLState: 22019
2017-07-26 12:37:36 [http-nio-7080-exec-1] ERROR:: ORA-00911: invalid character
update error javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
You don't need the semicolon at the end of the query and please use proper whitespacing. In the FROM clause, you don't have the whitespace between the subquery and the FROM keyword.
Note: don't forget to commit/rollback the transaction at the end and handle the exceptions as well. I hope this was just a sketch to show us the problem and not a code from a real world application.

JPA - Select All Rows from Dynamic Table Name

Hi guys I am new to jpa, named queries, etc.. and I need something like this:
select t from :tableName t
Later in code I want something like this:
em.createQuery(...);
setParameter("tableName", "Person")
Result would be:
select * from person
How to write such a generic jpa query statement allowing to select all rows from :tableName which may be defined at runtime? thanks in advance
Try this I think this works well
EntityManagerFactory emfactory=Persistence.createEntityManagerFactory("Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager();
Query query = entitymanager.
createQuery("Select p from Person p");
List<String> list = query.getResultList();
setParameter("foo", foo) is used to set the value for column of the table not to set the table name. I do not think it will work, as you want to set the table name dynamically.
You can try this:
public returnType foo(String tableName){
String jpql = "SELECT t FROM " + tableName+ " t";
Query query = em.createQuery(jpql);
//rest of the code
}

Hibernate - Get all table names in a Database

I am trying to get all the table names in a database(Oracle 11g) to dynamically generate checkboxes for each table in the UI. I have not mapped any of these tables in the .cfg.xml file.
I used the below code :
List<Object> list = sessionProd.createQuery("select table_name from user_tables").list();
for(Object l : list){
System.out.println("L : " +l.toString());
}
But it errored as below :
org.hibernate.hql.internal.ast.QuerySyntaxException: user_tables is not mapped [select table_name from user_tables]
Please let me know if there is any way to get all table names in Hibernate 4
You need to use SQL query, not HQL query
sessionProd.createSQLQuery("select table_name from user_tables").list();
Using a native SQL query method resolved the problem. Thanks for your suggestions.
The following code worked for me:
List<Object> list = sessionProd.createSQLQuery("select table_name from user_tables").list();
I think the query is not proper. Try with the below snippet
List<Object> list = sessionProd.createQuery("show tables from Database_name").list();
change the query string with select table_name from all_tables
List<Object> list = sessionProd.createQuery("select table_name from all_tables").list();
for(Object l : list){
System.out.println("L : " +l.toString());
}
Hibernate would return Exception to you in such case because you have not mapped user_tables. If you want to get all table names you should to create SQLQuery, that would return to you that you need. You can use HQL (createQuery) only for mapped tables

select scope_identity() using createSQLQuery in Hibernate

I am forced to use createSQLQuery to insert values into tables with an Identity column (the first column and the primary key) using hibernate. Using hibernate classes are not an option since the tables are created on the fly for each customer that is added to the system. I have run the query and it successfully inserts into the table. I then execute a "select scope_identity()" and it always returns null. "select ##Identity" works but that is not guaranteed to be the correct one. I have also tried to append "select scope_identity()" to the insert query. Then I tried query.list() and query.uniqueResult() both of which throw the hibernate exception of "No Results ..."
Session session = DatabaseEngine.getSessionFactory().openSession();
String queryString = "insert into table1 (dataid) values (1)"
SQLQuery query = session.createSQLQuery(insertQueryString);
query.executeUpdate();
query = session.createSQLQuery("select scope_identity()");
BigDecimal entryID = (BigDecimal)query.uniqueResult();
The simple example table is defined as follows:
"CREATE TABLE table1 (EntryID int identity(1,1) NOT NULL," +
"DataID int default 0 NOT NULL, " +
"PRIMARY KEY (EntryID))";
Is there a way I am missing to use scope_identity() with createSQLQuery?
Actually the SQLServerDialect class used by Hibernate uses the same "scope_identity()" too.
The reason why it's not working is because you need to execute those in the same statement or stored procedure.
If you execute the scope_identity() call in a separate statement, SQL Server will not be able to give you last inserted identity value.
You cannot do it with the SQLQuery, even Hibernate uses JDBC to accomplish this task. I wrote a test on GitHub to emulate this and it works like this:
Session session = entityManager.unwrap(Session.class);
final AtomicLong resultHolder = new AtomicLong();
session.doWork(connection -> {
try(PreparedStatement statement = connection.prepareStatement("INSERT INTO post VALUES (?) select scope_identity() ") ) {
statement.setString(1, "abc");
if ( !statement.execute() ) {
while ( !statement.getMoreResults() && statement.getUpdateCount() != -1 ) {
// do nothing until we hit the resultset
}
}
try (ResultSet rs = statement.getResultSet()) {
if(rs.next()) {
resultHolder.set(rs.getLong(1));
}
}
}
});
assertNotNull(resultHolder.get());
The code uses Java 8 lambdas instead of anonymous classes, but you can easily port it to Java 1.7 too.

"super-dynamic" query with MyBatis

Is there way to create sql query on the fly with MyBatis? To concretize: I have a query, where part of it (but not parameter) needs to be created in the runtime:
with dummy (id) as (
values (#{rangeEnd}) union all
select id - 1 from dummy where id - 1 >= #{rangeStart}
).......
The second part can be used as parameter, but, when trying the query as it is I get an exception:
[SQL0584] NULL or parameter marker in VALUES not allowed.
With plain JDBC I use MessageFormat:
PreparedStatement ps = connection.prepareStatement(
MessageFormat.format(MY_QUERY, currentRange.getRangeEnd()))
, but I haven't found a way how to do it with MyBatis.
It's really easy (answer from Dynamic Select SQL statements with MyBatis):
with dummy (id) as (
values (${rangeEnd}) union all
select id - 1 from dummy where id - 1 >= #{rangeStart}
).......
Use #SelectProvider annotation:
public interface SqlMapper {
static class PureSqlProvider {
public String sql(String sql) {
// Create your query here
return sql;
}
}
#SelectProvider(type = PureSqlProvider.class, method = "sql")
public List<Dummy> select(String sql);
}

Categories