i want to get alias column name and value in java spring hibernate - spring

String mainQuery = "select x as CONDITION_"+i+" from xyz";
SQLQuery sqlQuery = this.getSession().createSQLQuery(mainQuery);
from this query i will get allias column like
CONDITION_x
------------
value_x(anything)
here x is int value it will increment 0,1,2...
From this i want Json like ,
[
{
"CONDITION_0" :"value",
"CONDITION_1" :"value"
}
]
And this is in spring hibernate.
Please help,TIA.

Use hibernate ResultTransformer's which converts SQLQuery result to Map<k,v> object with the alias column name in query as the k-key and row value as v-value.
String mainQuery = "select x as CONDITION_"+i+" from xyz";
SQLQuery sqlQuery = this.getSession().createSQLQuery(mainQuery);
List<Map<String,Object>> result = sqlQuery.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
By this you can get the json result as you expected.

Related

Spring JPA - Custom function with array input

I have the following function script:
CREATE or REPLACE FUNCTION test1(_ids bigint[])
RETURNS TABLE
(
businessId BIGINT,
businessName VARCHAR
)
LANGUAGE plpgsql
AS
$$
BEGIN
RETURN QUERY (
SELECT id, name
FROM business b
WHERE id = any(_ids)
);
END;
$$
I can do the following and it works fine in normal psql commands:
SELECT * FROM test1(ARRAY [1,2,3])
How can I do this in Java? I tried passing an array of long, but it throws an sql grammar error.
repository:
#Query(nativeQuery = true, value = "SELECT * FROM public.test1(?)")
List<TestView> test1(long[] ids);
service:
long[] ids = {1L, 2L, 3L};
return businessRepository.test1(ids); // <-- does not work
If this is the incorrect way to pass an array / list of ids as an input parameter to a psql function, please advise.
Use a list rather than an array
#Query(nativeQuery = true, value = "SELECT * FROM public.test1(:ids)")
List<TestView> test1(#Param("ids") List<Long> ids);
Long[] ids = {1L, 2L, 3L};
return businessRepository.test1(Arrays.asList(ids));

How to Dynamically Retrieve JDBC ResultSet Data

The requirement is :-
The application will run dynamic SQLs and show the results in table format in JSP. The SQL passed to the application will change, which means the number, name, datatype of selected columns will change and so the result set will also change. The SQL is stored in a config.properties file, everytime we need to run a different SQL, we will just change the SQL in config.properties file. After the SQL is executed, from the ResultSet's Metadata object I have retrieved the column names and column datatypes by :-
ResultSetMetaData rsmd = rs.getMetaData(); // rs is the ResultSet
HashMap<String , String> hmap = new LinkedHashMap<String , String>();
for(int i=1;i<=rsmd.getColumnCount();i++)
{
hmap.put(rsmd.getColumnName(i), rsmd.getColumnTypeName(i));
}
hmap.entrySet().forEach(entry ->{System.out.println(entry.getKey() + " : " + entry.getValue());});
Output :-
TRADER : VARCHAR2
TRAN_NUM : NUMBER
STARTTIME : DATE
ERROR_DETAILS : CLOB
In JDBC, we have specific methods eg. rs.getString(columnName), rs.getInt(columnIndex), rs.getTimestamp(), rs.getClob() to get data of different data types. But in this scenario everything is dynamic, as columnName and columnDatatype will change everytime.
The ResultSet contains around 2000 rows.
How to write the logic, to check the column's datatype and apply the correct rs.getXXX() method to retrieve the ResultSet's data dynamically ?
Thanks & Regards
Saswata Mandal
I am able to do it by :-
while(rs.next())
{
JsonObject jsonRow = new JsonObject();
for(String colName : ResultSetColumnNames)
{
jsonRow.addProperty(colName, rs.getObject(colName)==null ? "NULL": rs.getObject(colName).toString());
}
jsonArry.add(jsonRow);
}
Thanks and Regards
Saswata Mandal

Is it possible to dynamic query to stored procedure?

I have a Spring boot application. I need a feature to dynamically query the stored procedure. What I mean by dynamically,
#NamedNativeQuery(name = "getCustomFoo", query = "select * from SP_FOO_CUSTOM where id = 1", resultClass = Foo.class)
but id could be any attribute in result set, so it could change based on the users input;
#NamedNativeQuery(name = "getCustomFoo", query = "select * from SP_FOO_CUSTOM where fooid = 1 ", resultClass = Foo.class)
Is it possible to do something like this? or this is totally out of standards?

How to create a temporary column + when + order by with Criteria Builder

here is the sql statement I am trying to translate in jpa :
select
id,
act_invalidation_id,
last_modification_date,
title,
case when act_invalidation_id is null then 1 else 0 end as test
from act order by test, last_modification_date desc
The actual translation
Root<Act> act = query.from(Act.class);
builder.selectCase()
.when(builder.isNull(actRoot.get("actInvalidation")), 1)
.otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);
Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);
query.select(act).orderBy(byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();
I try to create a temporary column (named test) of Integer type and orderby this column, then orderby lastmodificationdate. The content of this new column is determined by the value of actInvalidation field.
In short: How to create a temp column with integer values, then order by this temp column in jpa ?
Thank you
I didn't test this but it should work like this:
Root<Act> act = query.from(Act.class);
Expression<?> test = builder.selectCase()
.when(builder.isNull(actRoot.get("actInvalidation")), 1)
.otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);
Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);
Order byTest = builder.asc(test);
query.select(act).orderBy(byTest, byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();

How to get the data in query(search result of hql)?

I am a novice to use jdbc and I have some problems.
I use hql to search data in MySQL, and the result is Query type. I don't know how to get the data from the "Query".This is my code:
final String hql = "select app.appkey,app.type from " + getClassName() +
"app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
Thanks a lot.
You have to do the following:
final String hql = "select app.appkey,app.type from " + getClassName() + " app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
query.list(); //or query.getSingleResult();
query.list() will give a list of results.
query.getSingleResult() will give you a object.
You can check this.
If you are expecting a list of results, so:
List<Object[]> results = query.getResultList();
If you are expect one single result:
Object[] result = query.getSingleResult(); // if more than one result was found, this method will throw a NonUniqueResultException
If column information will be stored in a position of the Object array. Example:
String appKey = (String) result[0];
String appType = (String) result[1];
But work with Object array is not good. Try to use Dto, like explained here.

Resources