Hibernate - Get all table names in a Database - java

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

Related

Commons DBUtils Oracle 11.2.0.4 with Java 1.7 Binding parameters SQLException ORA-00942

I'm working with Oracle Database 11.2.0.4 with ojdbc6.jar, and I'm using apache commons dbutils v1.7, with JDK 7. So I'm using the QueryRunner and its method in this function
private <T> List<T> executeQueryAndReturnBeanList(String query, Class<T> className, Object... param) throws SQLException {
Connection connection = getDBConnectionInstance();
DbUtils.loadDriver("oracle.jdbc.driver.OracleDriver");
ResultSetHandler<List<T>> beanListHandler = new BeanListHandler<>(className,new BasicRowProcessor(new GenerousBeanProcessor()));
QueryRunner runner = new QueryRunner();
List<T> list = runner.query(connection, query, beanListHandler, param);
return list;
}
and everything works fine with select query without binding parameters
SELECT * FROM PEOPLE WHERE GRUPPO = 1 AND LANG = 'en_US'
But when I excute this query
String query = "SELECT * FROM PEOPLE WHERE GRUPPO = ? AND LANG = ?";
It gives me this SQL Exception
java.sql.SQLException: ORA-00942: table or view does not exist
Query: SELECT * FROM PEOPLE WHERE GRUPPO = ? AND LANG = ? Parameters: [1, en_US]
at org.apache.commons.dbutils.AbstractQueryRunner.rethrow(AbstractQueryRunner.java:527)
at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:391)
at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:252)
at mypackage.executeQueryAndReturnBeanList(JDBCFunctions.java:199)
I really don't know why. I tried to use :P1, :P2 or :1, :2 instead of ? to bind parameters but nothing it happens. Any ideas?
Group is a reserved word and cannot be used as a column or table name. Most probably you have a quoted column name such as "GROUP" within the table.
So, need to query as
SELECT * FROM PEOPLE WHERE "GROUP" = 1 AND LANG = 'en_US'
Quoted table names should be case sensitive, unlike unquoted ones.
The above one is the basic mistake, while the error(ORA-00942) suggests that your application connects to different schema than the schema in which successfully tested the query.
I finally found the solution. I inserted " on every column and table's name and now it works. For example:
String query = "SELECT * FROM \"PEOPLE\" WHERE \"GRUPPO\" = ? AND \"LANG\" = ?"

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
}

How to call oracle function using Hibernate criteria?

I am new to Hibernate. I am building a Login Portal. We have used DB Function to encrypt User Password. It seems that using hibernate for complex queries/functions/procedures on existing databases is difficult.
Is it possible to write below queries using Hibernate criteria?
SQL Query 1 :
SELECT first_name
FROM user.emp_group
WHERE username = 'XXX'
AND user.decrypt(password, 2) = 'YYYY';
SQL Query 2 :
SELECT a.DESC
,b.total
FROM user.STATUS a
,(
SELECT STATUS
,count(*) total
FROM user.emp
GROUP BY STATUS
) b
WHERE a.TYPE = b.STATUS (+)
User is the schema name and decrypt is function name.
I also faced problem for getting data from views which was resolved by this Stackoverflow post. How hibernate retrieve data from existing database view?
Thanks for that.
You can use native SQL with hibernate.
The way is something like this (for example):
String sql = "SELECT first_name, salary FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
List data = query.list();
for(Object object : data)
{
Map row = (Map)object;
System.out.print("First Name: " + row.get("first_name"));
System.out.println(", Salary: " + row.get("salary"));
}

ObjectNotFoundException: No row with the given identifier exists Hibernate

I have the next query :
String queryString = "from Visit vis "
+ "LEFT OUTER JOIN FETCH vis.pdv vis_pdv ";
return query.list();
After that, I get the next error when I try to access to some pdv:
nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists
The point is I have some corrupt data, so "Visit" has sometimes an id in "pdv" but it doesn't exist that pdv in the table "PDV". I would like to handle this in the query, so it doesn't return corrupt data. Is there any way?
Thanks
There's a similar issue here: org.hibernate.ObjectNotFoundException: No row with the given identifier exists: Single table query
Basically the answer is: you need to have a consistent database before Hibernate can work with the data.
I understood that you have a Visit.pvd column that is a foreign key into the PVD table but contains data that isn't reflected in PVD. That's your integrity violation. What you can do is bypassing Hibernate and collect any Visit.ids that are identifying entities that are invalid:
session.createSQLQuery("SELECT id FROM Visit "
+ "WHERE pvd NOT IN (SELECT p.id FROM pvd)").list();
This gets you a List<Object[]> that you can iterate to get the offending entities. Use that to UPDATE them to not contain invalid references (or just use a plain UPDATE with the WHERE clause I gave).
In hibernate whene you use join in HQL it returns List so please cast your return satement as return
List<Object[]> query.list();
and retrun type as
List<Object[]>
and for your question
try like this
select vis from Visit vis, Pdv pdv where vis.id=pdv.vis.id
this query will return
List<Visit>
String queryString = "from Visit vis "
+ "LEFT OUTER JOIN FETCH vis.pdv ";
return query.list();
you dont need List<Object[]> as your returning List<Visit>
List<Object[]>
is needed when you are returning multiple object from the query.
eg select v.pid,v.pname,v.pvisit from Visit v

hql error in select clause

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());
}

Categories