How to set MyBatis Spring replace null values with text NULL in SQL statements? - spring

I check existsing of row like this.
#Select("SELECT id FROM ${table_path} " +
"WHERE id = ${cluster_id} AND " +
"id_second = ${node_id} AND " +
"resource_type_id = ${resource_type_id}")
BillingData isRecordExist(#Param("table_path") String tablePath,
#Param("cluster_id") Integer clusterId,
#Param("node_id") Integer nodeId,
#Param("resource_type_id") Integer resourceTypeId);
But sometimes there is no resource_type_id and I get statements like this:
"SELECT id FROM tablename WHERE id = 1 AND id_second = 2 AND resource_type_id = "
It's not valid and my app crashes. How can i set up batis to replace null value params with NULL text?
I tried search on internet. Settings param 'jdbcTypeForNull' doesn't affect. Type converters can't help me too

Related

How to query the database based on current day using Hibernate?

I would like to retrieve database items based on the current day.
For that purpose I am trying to use the day() function as explained there and mentioned there.
I have a 'created' date field that is automatically filled when a new item is created in the table. It's configured using a model, like that:
#Column(name = "created", nullable = false)
#CreationTimestamp
private Date created;
I created a couple of items and the date is filled in the database as expected.
Now I am trying to call those items using a HQL query:
String hql = "" +
"FROM Item as item " +
"WHERE item.itemId = ?1" +
"AND item.created = day(current_date())";
The problem is that this query is returning a NoResultException.
It's weird because I am using the current_date() function in other scenarios, e.g.:
String hql = "" +
"FROM Item as item " +
"WHERE item.itemId = ?1" +
"AND item.createdAt >= current_date - ?2";
And it is working pretty well!
So I assume the issue is related with day() function.
Try use this:
String hql = "" +
"FROM Item as item " +
"WHERE item.itemId = ?1" +
"AND date(item.created) = current_date()";

How can i add a QueryHint to a Hibernate Custom Query?

I'm trying to add the Oracle Query Hint /*+ GATHER_PLAN_STATISTICS PARALLEL(16) */ to my Custom Query which looks similar to this:
#Query("SELECT " +
" FROM myTable tab " +
" WHERE tab.create_date >= to_date(:dateFrom) " +
" AND tab.create_date < to_date(:dateTo)")
List<MyModel> findEntriesByDate( #Param("dateFrom") String dateFrom, #Param("dateTo") String dateTo);
I cannot find any way to make this work. I tried various things, for example adding this on top of the method:
#QueryHints({
#QueryHint(name = org.hibernate.annotations.QueryHints.COMMENT, value = "GATHER_PLAN_STATISTICS")
})
or
#QueryHints({
#QueryHint(name = GATHER_PLAN_STATISTIC, value = "GATHER_PLAN_STATISTICS")
})
Is there a way to make this work or do I have to change my approach?

How to pass Byte value to JPQL in Spring?

I have an Interface wich
extends JpaRepository
I have method in it:
#Query("SELECT a FROM ArticlesEntity a " +
"WHERE ((:approved = 2 ) or (a.approved = :approved)) ")
Page<ArticlesEntity> filterByAllPage(
#Param("approved") Byte approved,
Pageable pageable);
When this method is invoked I have an exeption:
java.lang.IllegalArgumentException: Parameter value [2] did not match expected type [java.lang.Integer (n/a)]
When I change
(:approved = 2 )
to
(:approved is null)
or
#Param("approved") Byte approved
to
#Param("approved") Integer approved
or
"WHERE ((:approved = 2 ) or (a.approved = :approved))"
to
"WHERE (a.approved = :approved) "
it works.
It seems that should be something like
(:approved = (byte) 2 )
or
(:approved=2.byteValue())
but both didn't work also.
Is there any way to use Byte here or it's better to switch to Integer ?
The database is MySQL and it has table "articles" with column "approved" of "TINYINT(1)" type.

Bind parameters for ORDER BY in NamedParameterJDBCTemplate

I am trying to use NamedParameterJdbTemplate in a Spring MVC application. The issue is that the bind parameters do not seem to work (no sorting happens) when I include one of ORDER BY clauses listed below. However, a hard coded order by column name in the sql works.
ORDER BY column1
ORDER BY column1
ORDER BY column1 asc
ORDER BY column1 desc
For example, the below listed query does not work.
private static final String SEARCH_ALL_BY_SORT_ORDER=
" select FIRST_NM, MIDDLE_NM, LAST_NM, CUSTOMER_IDENTIFIER, EMAIL_ADDRESS, ACCOUNT_ID" +
" from VIEW " +
" where CUSTOMER_IDENTIFIER= :customerIdentifier " +
" and ( REGEXP_LIKE(FIRST_NM, :firstName, 'i') " +
" or REGEXP_LIKE(LAST_NM, :lastName, 'i') " +
" or REGEXP_LIKE(EMAIL_ADDRESS, :emailAddress, 'i') )" +
" order by :sortColumns";
The same query with a hard coded order by column works:
private static final String SEARCH_ALL_BY_SORT_ORDER=
" select FIRST_NM, MIDDLE_NM, LAST_NM, CUSTOMER_IDENTIFIER, EMAIL_ADDRESS, ACCOUNT_ID" +
" from VIEW " +
" where CUSTOMER_IDENTIFIER= :customerIdentifier " +
" and ( REGEXP_LIKE(FIRST_NM, :firstName, 'i') " +
" or REGEXP_LIKE(LAST_NM, :lastName, 'i') " +
" or REGEXP_LIKE(EMAIL_ADDRESS, :emailAddress, 'i') )" +
" order by LAST_NM";
Here's the relevant jdbctemplate code
Map <String, Object> params = new HashMap <String, Object>();
params.put("customerIdentifier", customerIdentifier);
params.put("firstName", searchCriteria );
params.put("lastName", searchCriteria );
params.put("emailAddress",searchCriteria);
// sortBy is COLUMN name
// sortOrder is either 'asc' or 'desc'
params.put("sortColumns", sortBy + " " + sortOrder);
// Using just the column name does not work either
//params.put("sortColumns", sortBy);
namedParameterJdbcTemplate.query(SEARCH_ALL_BY_SORT_ORDER, params, new MemberMapper());
Only values can be bound as parameters. Not parts of the query itself.
In the end, a prepared statement is generated and the parameters are bound to the prepared statement. The principle of a prepared statement is to prepare the execution plan of the query (of which the order by clause is a part), and to execute the query one or several times after, with varying parameters.
If the query is not complete, the execution plan can't be prepared and reused. So, for this part of the query, you'll need to generate the query dynamically using string concatenation, and not parameters.
As JB Nizet has already explained that parts of query cannot be used as bind keys (orderby :age). Therefore we will need to use concatenation here instead.
" order by "+ sortBy + " " + sortOrder;

JDBC ResultSet get column from different tables

i wan to retrieve data from query involving many tables.
i have a query as follows
String sql = "SELECT "
+ "s.Food_ID AS 'Sales_FoodID', "
+ "f.Food_Name AS 'foodName' "
+ "FROM Ordering o, Sales s, Food f"
+ " WHERE o.Table_No = " + tableNo + ""
+ " AND o.Paid = '" + NOT_PAID + "'"
+ " AND s.Order_ID = o.Order_ID"
+ " AND f.Food_ID = s.Food_ID;";
resultSet = statement.executeQuery(sql);
no error were found when i run the program, but after i add this line to get a table's column data:
String orderID = resultSet.getString("foodName");
i'm given this error:
java.sql.SQLException: Column not found
anyone know why?
You have to use next() method.
You should know that ResultSet is implicitly positioned on position before first row so you need to call next to get current position and if is valid, it returns true, else returns false (cursor is positioned after the last row).
rs = statement.executeQuery(sql);
while (rs.next()) {
String orderID = rs.getString(2);
}
Note: You can use also rs.getString(<columnName>) but in case when you know how your statement looks i recommend to you use index instead of columnName.
After calling the resultSet.executeQuery() you need to call the next() to pulling the records from db
after that you can call setXxx() provided by Java API

Resources