MySQL - Hibernate SQL Query - java

I created a query like this in my project with hibernate connected to a mysql database:
String sqlQuery = "select e.EXPEDITE_NUM_DISPLAY from receiver e where e.ID = 113";
List<Object> rows = session.createSQLQuery(sqlQuery).list();
The result list (rows) is a list with only one element with value = null (Ex. rows: [null]).
When i run the same query in MySQL workbench the value of the column is presented.
Any idea why in hibernate the returned value is null and not the right value?

Related

Spring Boot - NamedParameterJdbcTemplate giving incorrect count of rows affected

In my DAO repository class below is the implementation
//Return the number of rows affected
public int deleteFeed(long feedId) {
String sqlQuery = "UPDATE feed SET trash = TRUE WHERE id = :id";
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("id", feedId);
return namedParameterJdbcTemplate.update(sqlQuery, paramSource);
}
For the same feedId passed every time, the count result comes as 1 for the number of rows affected. If I run the same query in MySQL workbench, I am getting 0 rows affected.
Note: I am pointing to same DB in app and workbench.

Create table as select with parameter using jdbcTemplate

I want to use jdbcTemplate to create table based on another table under condition. I have postgres database. When I execute this and pass parameter:
String SQL = "create table test as (select * from users where countryId =?)";
jdbcTemplate.update(SQL, new Object[] {3})
I receive table test with all columns from users table but with no rows.
However, when I execute this:
String SQL = "create table test as (select * from users where countryId =3)";
jdbcTemplate.update(SQL)
I receive test table with rows where countryId = 3, so that is what I was expecting to receive in the first solution.
Your passing of the bind variable is not correct, but it does not play any role.
You simple can not use a bind variable in a data definition statement as you immediately see in the triggered error
Caught: org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL
[create table test as (select * from users where countryId =?)];
SQL state [72000]; error code [1027];
ORA-01027: bind variables not allowed for data definition operations
So you have two options, either concatenate the statement (which is not recommended due to the danger of SQL injection)
or split the statement in two parts:
// create empty table
sql = "create table test as (select * from users where 1 = 0)";
jdbcTemplate.update(sql)
// insert data
sql = "insert into test(countryId, name) select countryId, name from users where countryId =?";
updCnt = jdbcTemplate.update(sql, new SqlParameterValue(Types.INTEGER,3));
Note that in the insert statement you can see the correct way of passing an interger value of 3 as a bind variable.
You can follow below approach as well:-
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)");
List<Object[]> employeeIds = new ArrayList<>();
for (Integer id : ids) {
employeeIds.add(new Object[] { id });
}
jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds);
Here you may query with 2 operations to avoid SQL injection.
You are using method update from jdbcTemplate in a wrong way.
Try with this:
String SQL = "create table test as (select * from users where countryId = ?)";
jdbcTemplate.update(SQL, 3);

List of columns in sql query

I have a query using various joins, and I just need the list of columns which are returned by this query. I done it in java, by asking only one row with rownum=1 and getting column name for value.The problem is if there is no data returned by that query.
For ex.
select * from something
and if there is any data returning by this query then it will return col1,col2,col3.
But if there is no data returned by this query, then it will throw error.
What I need is
Is there any way that I can run
desc (select * from something)
or similar to get list of columns returned by query.
It can be in sql or JAVA. Both methods are acceptable.
In my application, user passes the query, and I can add wrapper to the query but I cant modify it totally.
The flow of application is
query from user -> execute by java and get one row -> return list of columns in the result set.
you can use ResultSetMetaData of resultset
for example :
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int countOfColumns = rsmd.getColumnCount();
for(int i = 1; i <= countOfColumns ; i++ )
System.out.println(rsmd.getColumnName(i));
you could maybe convert your query to a view, you can then see the columns in the view by querying user_tab_columns
select * from user_tab_columns
The Oracle equivalent for information_schema.COLUMNS is USER_TAB_COLS for tables owned by the current user, ALL_TAB_COLS or DBA_TAB_COLS for tables owned by all users.
Tablespace is not equivalent to a schema, neither do you have to provide the tablespace name.
Providing the schema/username would be of use if you want to query ALL_TAB_COLS or DBA_TAB_COLS for columns OF tables owned by a specific user. in your case, I'd imagine the query would look something like:
String sqlStr= "
SELECT column_name
FROM all_tab_cols
WHERE table_name = 'users'
AND owner = ' || +_db+ || '
AND column_name NOT IN ( 'password', 'version', 'id' )
"
Note that with this approach, you risk SQL injection.

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

Mysql - result the data's with or with out available in DB

This is my sql query to sum the error count in DB. What made the problem below is, when I check the available data in this, it retrieve the actual and correct data given, if I'm giving any wrong (that is unavailable data in table) input it gives nothing that is it doesn't throw any output screen:
SELECT
SUM(IF(ieb.errortype_id='1',1,0)) AS Total_Critical,
SUM(IF(ieb.errortype_id='2',1,0)) AS Total_Non_critical,
u.emp_id,
u.emp_name
FROM
issueerror_empmap iem,
issueerror_body ieb,
USER u,
issueerror_type iet
WHERE
ieb.chapter_id = '424262' AND
iem.chapter_errorid=ieb.chapter_errorid AND
iem.emp_id = u.emp_id AND
u.emp_id = '693' AND
ieb.errortype_id=iet.errortype_id
GROUP BY
iem.emp_id,
u.emp_name
ORDER BY
iem.emp_id
Can any one please suggest me how to build this query to retrieve the data if available and display the output as null if the input data not available in a table.
For producing the output for the above query is (if data available in a table):
Total_Critical Total_Non_Critical emp_id emp_name
4 10 xxx xxx
For producing the output for the above query is (if data not available in a table):
Total_Critical Total_Non_Critical emp_id emp_name
I am expecting the emp_id and emp_name with the error count as null or zeroes.
how about this query?
select
sum (Total_Critical) as Total_Critical,
sum(Total_Non_critical) as Total_Non_critical,
emp_id,
emp_name from
(
(SELECT
SUM(IF(ieb.errortype_id='1',1,0)) AS Total_Critical,
SUM(IF(ieb.errortype_id='2',1,0)) AS Total_Non_critical,
u.emp_id,
u.emp_name
FROM
issueerror_empmap iem,
issueerror_body ieb,
USER u,
issueerror_type iet
WHERE
ieb.chapter_id = '424262' AND
iem.chapter_errorid=ieb.chapter_errorid AND
iem.emp_id = u.emp_id AND
u.emp_id = '693' AND
ieb.errortype_id=iet.errortype_id
GROUP BY
iem.emp_id,
u.emp_name
ORDER BY
iem.emp_id )
) UNION ALL (
select 0,0,null, null
)
) as tbl1

Categories