Number of characters in sql query result - java

I am using Spring 3.1.1 with Hibernate 4 and a MSSQL database. Finally, I have been able to query my database with joins in my table that returns the correct answers. Although, it seems that it does not return the entire strings of my messages, but cuts at 29/30 digits. Here is my query:
SQLQuery sql = this.getCurrentSession().createSQLQuery(
"SELECT event.id as eventid, CAST(event_type.type_name AS varchar) as eventtype, event.check_date, event.event_date, event.status, CAST(event_message.message AS varchar) as eventmessage " +
"FROM event_log event " +
"LEFT JOIN event_type " +
"ON (event.event_type_id = event_type.id) " +
"LEFT JOIN event_message " +
"ON (event.event_message_id = event_message.id) " +
"WHERE event.event_type_id = " + jobId +
"ORDER BY eventid");
The result can be:
4506 Database 2014-01-15 14:14:15.02 2014-01-15 14:14:15.02 false Database-connection cannot be
Where the columns are id, task_name, check_date, event_date, status and the message-string at the end. .
The result goes to a ArrayList<Object[]> where I read row[0] etc. to get the entities in the row. The string message gets cut after 29 digits, which is disturbing. Why does it cut the string and how can I fix this? In my database the string exists in it's full and is entitled 400 characters max.
I know this is probably not the best way to query my database, but it will do for my application since it works.

You are using varchar without a length. Never do this!
Replace:
CAST(event_type.type_name AS varchar)
With something like:
CAST(event_type.type_name AS varchar(255))
In some contexts, the default length is 32. In some it is 1. In general, though, always specify the length.
EDIT:
Actually, you probably don't even need the cast. Why not just have event_type.type_name in the select list?

Related

How to CAST twice an element in a row JPA

I've done a query with PostgreSQL that retrieves certain data as I expected: (It works)
SELECT distinct d.data
FROM myScheme.myTable d, myScheme.mySecondTable g, json_array_elements(d.data->>'categorys') e
where d.data->>'categorys' is not null
AND e::text::int in (g.id_product_category_magento)
AND e::text::int IN (21718, 17);
The problem is when I try to do the same query with Java using JPA. This is not worked script:
#Query(
nativeQuery = true,
value = "SELECT DISTINC d.data " +
"FROM myScheme.myTable d, myScheme.mySecondTable g, " +
"json_array_elements(d.data->>'categorys') e " +
"where d.id = :id AND d.data->>'categorys' is not null " +
"AND CAST(CAST(e as text) as Integer) in (g.id_product_category_magento) " +
"AND CAST(CAST(e as text) as Integer) IN (:categories)"
)
List<ServiceDefinition> yest(Set<Long> categories, #Param("id") Long id);
The stack trace throws the following error message:
No dialect for Mapping JDBC 1111
Things to keep in mind:
b.data ->> 'categorys' is an array of Strings that contains string values such as: ['123', '456', '789'] and should return each one of this values.
Pd: I'm not sure if this is the right way to cast a value twice: AND CAST(CAST(e as text) as Integer).
I found the solution to this:
I saved from casting each element twice by using json_array_elements_text instead of json_array_elements, the first one returns the values already as Strings. The second one was producing this error message: No dialect for mapping 1111 due to a bad cast syntax made by me. This thanks to the wonderful suggestion from #AdrianKlaver
Doing select d.data seemed not to work, because it was returning an unknown data type for Hibernate, instead I returned d.idbecause I was really expecting each categoryId as Long type.
Used this CAST(e as int4) instead of this as Integer
Removed an extra #Param (id) of my yest() method
The final query is as shown below:
#Query(
nativeQuery = true,
value = "SELECT distinct d.id FROM myScheme.myTable d, myScheme.mySecondTable g " +
",json_array_elements_text(d.data->>'categorys') e " +
"where d.data->>'categorys' is not null " +
"AND CAST(e as int4) in (g.id_product_category_magento) " +
"AND CAST(e as int4) in (:categories)"
)
List<Long> yest(List<Long> categories);
Hope this helps someone in the future. :)

How can I set a date variable with normal string variables in my jpql code?

I have a query that has to be executed in my application. On the front end side, a user should be able to make a search in the search bar. Every time he will write in the search box, we will automatically take this input and send a request to retrieve the corresponding data. The problem here is the date, the user should be able to select the data returned according to the specific categories. When he select a date, all the products with this corresponding date have to be returned.
This is the code below:
String sql = "SELECT t FROM tables t WHERE (t.a LIKE ?1 OR "
+ " t.b LIKE ?1 "
+ "OR t.c LIKE ?1 "
+ "OR t.d LIKE ?1 OR t.e LIKE ?1 "
+ "OR t.f LIKE ?1 "
+ "OR t.g LIKE ?1 "
+ "OR t.u_date LIKE TO_DATE(?1,'dd/MM/yyyy') "
+ "OR t.y_date LIKE TO_DATE(?1,'dd/MM/yyyy') ) "
+ "OR t.num LIKE ?2)";
lstMvt = em.createQuery(sql)
.setParameter(1,isDate == true ?search_value:search_value+"%")
.setParameter(2, num+"%")
.setFirstResult(start)
.setMaxResults(limit)
.getResultList();
In my code, I have written a helper function to check whether the search value entered is a date or a normal string. So when injecting the parameters, isDate variable tells me that if the search is true(a date) then inject it directly but if it is a normal string inject it with % as it is a LIKE clause.
The problem is being caused by the dates variable in the query. When I search with a date value in the search box the data return correctly, but when I try to search with a non-date value, an exception is thrown. I know the problem is from the dates variables because I had commented them to test and it was working properly.

Same Query Gives Different Output In MSSQL And Hibernate 3

Users
Userid
userName
password
status
Issue
IssueNum
issueDescription
status
creationdate
IssueAssigned
issueNumber
issueAssignedTo
issueAssignedBy
comments
In my primefaces datatable I am fetching these value using following query
SELECT I.issue_number, I.issue_describtion, U.first_name,US.first_name
FROM ISSUES I
LEFT JOIN ISSUE_ASSIGNED IA
ON I.issue_number = IA.Issue_number
LEFT JOIN USERS U
ON U.id = IA.assigned_to_user_id
LEFT JOIN USERS US
ON US.id = IA.assigned_by_user_id
The Admin who is also a user assigns issue to another user
In MSSQL this above query works fine gives me proper record for U.firstName and US.FirstName as they are different user.
query in MSSQL returns
PER-1675 Perform - Evaluation Form Export does not pull any data in Legacy Export Tool (Due 8/14) Ameh Sandip
PER-2048 Calculation of scores fails when the lower/upper bound value of a calculation text result is a Ameh Sandip
But in Hibernate for the same query both firstName and US.firstName gives same result
code
#Override
public List<Object> getIssueListForAssigingIssue (){
List<Object> allIssueList = getHibernateTemplate()
.getSessionFactory()
.getCurrentSession().createSQLQuery("SELECT I.issue_number, I.issue_describtion, IT.issue_type,U.first_name ,US.first_name "
+ "FROM ISSUES I "
+ "LEFT JOIN ISSUE_ASSIGNED IA "
+ "ON I.issue_number = IA.Issue_number "
+ "LEFT JOIN USERS U "
+ "ON U.id = IA.assigned_to_user_id "
+ "LEFT JOIN USERS US "
+ "ON US.id = IA.assigned_by_user_id ").list();
return allIssueList;
}
query in hibernate returns
PER-1675 Perform - Evaluation Form Export does not pull any data in Legacy Export Tool (Due 8/14) Ameh Ameh
PER-2048 Calculation of scores fails when the lower/upper bound value of a calculation text result is a Ameh Ameh
I was able to solve it by giving alias to both the column somehow hibernate gets confused between the two columns

case statement in select in jpql

I have tried the following but not working.
String mainQuerySt = "select o.progressStatus, "
+ " CASE WHEN o.assigneeEmployee IS NOT NULL THEN o.assigneeEmployee.fullNameSt ELSE '' END as assignee "
+ " from Tt o"
em.createQuery(mainQuerySt).getResultList();
What is wrong with this? Actually, I want to show assigneeEmployee full name if it is not null and otherwise an empty string.
I am using EclipseLink v2.1 as JPA
Thanks in advnace.
EclipseLink Tutorial
You are using o.assigneeEmployee IS NOT NULL, and I assume o.assigneeEmployee is a relationship. Using dot notation forces an inner join, which then will filter out nulls. Try
String mainQuerySt = "select o.progressStatus, "
+ " CASE WHEN assigneeEmployee IS NOT NULL THEN assigneeEmployee.fullNameSt ELSE '' END as assignee "
+ " from Tt o left outer join o.assigneeEmployee assigneeEmployee"
If it does not return the results expected, then you will need to turn on SQL logging to see the SQL produced, and show the results you do expect.

How to get meta data information of a sql query

I am using postgres 9.1 and java code for jdbc.
I may use a order by clause in my sql query string
I just want to get the meta data information of the query to find whether the query has order by clause or not. If it has then how many fields has been specified in the order by clause.
Ex:
order by age
order by age, name
order by age asc, name desc
In these example I just want to retrieve the number of parameters that are specified in the order by clause and their column names.
If your are getting your query as string you could simply parse it.
i.e. To figure out that ORDER BY is there
"SELECT * FROM MyTable ORDER BY SomeColumn".toLowerCase().indexOf("order by") // if it's return -1 query does not contains order by section otherwise it returns start index for first occurence "ORDER BY" in given string
For more complex searching in string you may need to use RegExp
You can do it by breaking an SQL query into part and then reassigning.
Like
String sql="SELECT NAME,COMPANY,FNAME,AGE FROM COMP_DATA JOIN PERSONAL_DATA WHERE (1=1) AND FNAME='Vaibs' ORDER BY AGE";
While writing in JAVA do as below.
Break Whole query into String parts and recombine it like this.
String strSQL = "SELECT " + "NAME"+",COMPANY"+",FNAME"+",AGE" + "FROM "
+ getTableName1(); //getTableName1() return tablename
strSQL+="JOIN "+ getTable2()+"";//getTable2() return tablename as well
String strWhere = " WHERE (1=1) " + " and FNAME='" + fname+ "';
String orderBySQL = " Order by " + i_will_return_string_to_order_by();
//return AGE in our case
String FinalString= strSQL +strWhere +orderBySQL ;
SOP order by to get what you want.
Hope that helped.

Categories

Resources