Alias Column In Resultset - spring

I have a query in backend spring project, where I create a field alias named agent_id but I don´t have that column in Model. What is the best approach for showing this as a field in table view in front end???.
Here´s the query:
Query query = em.createNativeQuery("SELECT" +
" ips.*, " +
" s.mls_id AS imported," +
" p.INTEGRATOR_SALES_ASSOCIATED_ID AS agent_id " +
"FROM test1.ilist_property_summary ips " +
" LEFT JOIN test1.statistics s ON s.mls_id = ips.INTEGRATOR_PROPERTY_ID " +
" LEFT JOIN test1.person p ON p.INTEGRATOR_SALES_ASSOCIATED_ID = ips.INTEGRATOR_SALES_ASSOCIATED_ID " +
"WHERE ips.AGENCY_ID = :agencyId AND (s.statistics_type = 1 OR s.statistics_type IS NULL) AND ips.ORIG_LISTING_DATE BETWEEN :startDate AND :endDate");
query.setParameter("agencyId", agencyId)
.setParameter("startDate", DateUtil.asDate(startDate), TemporalType.DATE)
.setParameter("endDate", DateUtil.asDate(endDate), TemporalType.DATE);
return (List<PropertyVO>) query.getResultList().stream().map(o -> processProperty((Object[]) o)).collect(Collectors.<PropertyVO>toList());
I already have a field that shows agent_id, but not fetched with same field of table Person. I need to retrieve that field agent id alias fetched from left join.

I followed another approach:
Query query = em.createNativeQuery("SELECT" +
" ips.id, ips.agency_id, ips.integrator_property_id, ips.orig_listing_date, ips.contract_type," +
" ips.transaction_type, ips.current_listing_price, ips.current_listing_currency, ips.apartment_number, ips.commercial_residential," +
" ips.commission_percent, ips.commission_value, ips.property_type, ips.street_name, ips.street_number," +
" s.mls_id AS imported," +
" p.INTEGRATOR_SALES_ASSOCIATED_ID AS INTEGRATOR_SALES_ASSOCIATED_ID" +
" FROM test1.ilist_property_summary ips " +
" LEFT JOIN test1.statistics s ON s.mls_id = ips.INTEGRATOR_PROPERTY_ID " +
" LEFT JOIN test1.person p ON p.INTEGRATOR_SALES_ASSOCIATED_ID = ips.INTEGRATOR_SALES_ASSOCIATED_ID " +
"WHERE ips.AGENCY_ID = :agencyId AND (s.statistics_type = 1 OR s.statistics_type IS NULL) AND ips.ORIG_LISTING_DATE BETWEEN :startDate AND :endDate ");
Here field
INTEGRATOR_SALES_ASSOCIATED_ID
is taken from table p, and not from ips. I just selected specific fields so this one could be taken from the other table.

Related

repeated data in json response spring boot

I have this SQL query
#Query( value = "select tc_users.id as userid,tc_devices.id as deviceid, tc_devices.name, tc_devices.lastupdate as hora_fecha,\n" +
"tc_positions.speed as velocidad, tc_positions.latitude, tc_positions.longitude, tc_positions.devicetime\n" +
"from tc_devices\n" +
"join tc_users on tc_users.id = tc_devices.userid \n" +
"join tc_positions on tc_devices.id= tc_positions.deviceid and \n" +
"tc_positions.devicetime=(select max(devicetime) from tc_positions where tc_positions.deviceid= tc_devices.id) and tc_users.id= ?1 ;", nativeQuery = true)
List<resumen_entity> resu(Integer userid);
This SQL query return this data
result of query in SQL workbench
but when using it with my spring project it returns this json
result of query by springboot
a really need help with this problem
I try with another type of SQL query but spring returns the same result
#Query( value = "select distinct tc_users.id as userid,tc_devices.id as deviceid, " +
"tc_devices.name, tc_devices.lastupdate as hora_fecha, " +
"tc_positions.speed as velocidad, tc_positions.latitude, " +
"tc_positions.longitude, tc_positions.devicetime " +
"from tc_users, tc_devices,tc_positions where tc_users.id =tc_devices.userid " +
"and tc_devices.id= tc_positions.deviceid " +
"and tc_positions.devicetime=(select max(devicetime) " +
"from tc_positions where tc_positions.deviceid = tc_devices.id) and tc_users.id= ?1 ",
nativeQuery = true)
List<resumen_entity> resu(Integer userid);

How to add a dynamic where in #Query?

I need to add my where conditions based in my filter object. If some value in the filter object is null, isn't necessary add the where condition of this parameter.
How to add a dynamic where?
Exemple:
FilterObject{
name: "Teste";
age: null;
}
#Query(value="SELECT id FROM user WHERE name = FilterObject.name", nativeQuery = true)
public List<User> getUsers(???)
Other example:
FilterObject{
name: "Teste";
age: 12;
}
#Query(value="SELECT id FROM user WHERE name = FilterObject.name AND age = FilterObject.age", nativeQuery = true)
public List<User> getUsers(???)
This is a highlevel example. Isnt the correct code. But... Is the necessary to understand my question
If a parameter of my filter is null this parameter isnt used in my where
Im Using spring boot with Spring Data JPA and my Query stay in my repository a Repository.
My Original request:
#Query(value = " SELECT "
+ " solicitacao.nm_orgao AS nmOrgao, "
+ " solicitacao.ds_ano_exercicio AS exercicio, "
+ " solicitacao.nm_organismo AS nmOrganismo, "
+ " dadosBancarios.valor AS valor, "
+ " dadosBancarios.valor * dadosBancarios.vl_taxa_cambio AS valorReais, "
+ " dadosFinanceiros.vl_dotacao_disponivel AS vlDotacaoDisponivel, "
+ " solicitacao.id_solicitacao AS codigoPagamento "
+ " solicitacao.tp_solicitacao_status AS idFase, "
+ " organismo.id_orgao AS idOrgao, "
+ " solicitacao.id_organismo AS idOrganismo, "
+ " pagamentos.id_status_pagamento AS statusPagamento "
+ " FROM "
+ " tbs_solicitacao solicitacao "
+ " JOIN tbs_dados_bancarios dadosBancarios ON solicitacao.id_solicitacao = dadosBancarios.id_solicitacao "
+ " JOIN tbs_dados_financeiros dadosFinanceiros ON dadosFinanceiros.id_solicitacao = solicitacao.id_solicitacao "
+ " JOIN tbs_organismo organismo ON organismo.id_organismo = solicitacao.id_organismo "
+ " JOIN tbs_pagamentos pagamentos ON dadosFinanceiros.id_dados_financeiros = pagamentos.id_dados_financeiros ",nativeQuery = true)
List<Object[]> getRelatoriosProgramacao();
You can use Spring Data JPA specifications:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications
You simply have to implement the method toPredicate:
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder);
In this method you get root, query and the CriteriaBuilder to create a Criteria API where predicate.
Event methods like findAll take a Specification.

Sub query with lambda expression

I need lambda expression for the below query.
select tb_device.lat,tb_device.lng,tb_device.speed,tb_device.trackedOn, IL.DeviceIcon, IL.speedLimit, " +
"IL.deviceId, IL.deviceName, tb_device.Location, tb_device.IsExist " +
"from( select CONVERT (DATE, max( trackedOn)) as trackedDate , inventoryLogId as InventoryId from tb_devicelog " +
"group by inventoryLogId) as tb " +
"inner join tb_devicelog as tb_device on tb.InventoryId=tb_device.inventoryLogId and " +
"tb.trackedDate= CONVERT (DATE, tb_device.trackedOn) " +
"inner join tb_inventorylog IL on tb_device.inventorylogid=IL.id " +
"inner join tb_Logins ln on IL.assignedToCustId = ln.customers_id where ln.userName = 'cadmin' and IL.id in(1,3,2 )"
You could try Linqer which is a SQL to LINQ converter:
http://www.sqltolinq.com/

Birt report parameter passing

Hi i have to pass parameter to a report...with a concat-date ....but its showing error...
like this...am having in list box with 2011-2012,2012-2013...here is my oracle query
DATE FOMART IN DATABASE:25-Mar-2012
oracle query
select tran_date,
ROUND (nvl(sum(WALKIN_WITHOUT_CGROUP),0)/ COUNT(*),2)APC
from OUTLET_PAYMODE_REPORT_FACT
Before Open:
var sqld= new String();
yearParam = params["Year"].value;
yearParam = yearParam.split("-");
startYear = yearParam[0];
endYear = yearParam[1];
this.queryText =this.queryText +" where TRAN_DATE between '" + startYear + "01-Mar-' and '" + endYear + "30-Mar-'"+
"group by tran_date"
but am getting error like this.....
org.eclipse.birt.report.data.oda.jdbc.JDBCException: SQL statement does not return a ResultSet object.
SQL error #1:ORA-01861: literal does not match format string
I think, your sql string should be
" where TRAN_DATE between '01-Mar-" + startYear +
"' and '30-Mar-" + endYear + "' " +
"group by tran_date"

Error in inserting the SQLqueries with special characters in to H2database

I have an xml which i parse to read the values of the nodes and i get these values in to a custom list for ex Validation.
Now after parsing the xml for values when i try to insert the values in to the table in the H2Database i end up getting the syntax error.
Sample xml which i parse
<DmtTask xsi:type="SqlTask">
<TaskSeverity></TaskSeverity>
<TaskCategory></TaskCategory>
<TaskTitle></TaskTitle>
<TaskMessage></TaskMessage>
<TaskCode></TaskCode>
<DSqlGenerated></DSqlGenerated>
<TaskName>VALIDATE_COMPANIES_MISSING_AVAILABILITY_DATE</TaskName>
<SqlQuery>DROP TABLE CLIENT_VALIDATION.COMPANIES_MISSING_AVAILABILITY_DATE IF EXISTS;
CREATE TABLE CLIENT_VALIDATION.COMPANIES_MISSING_AVAILABILITY_DATE AS
(SELECT * FROM CLIENT.COMPANIES WHERE AVAILABILITY_DATE = '');
</SqlQuery>
<ReportError>SELECT 'Missing Availability Date' AS ERROR_DESC,
ORGANIZATION_NAME,AVAILABILITY_DATE,COUNTRY,EMAIL_ADDRESS,INSTANT_MESSENGER_ADDRESS,REVERSE_DEBIT_CREDIT,KEEP_DEBIT_CREDIT_AND_REVERSE_SIGN
FROM CLIENT_VALIDATION.COMPANIES_MISSING_AVAILABILITY_DATE</ReportError>
<MetricSchemaName>DMTSCRIPTS</MetricSchemaName>
</DmtTask>
Dynamic Query which i wrote to update the table from code behind. TaskEditorText is an object of custom collection List
for (int i = 0; i < taskEditorText.Count; i++)
{
//string sqlGenerated = "false";
db.ExecuteNonQuery("INSERT INTO " + Schema + ".DMTScriptTasks(DmtScriptId,TaskSeverity,TaskCategory,TaskTitle,TaskMessage,TaskCode,TaskName,Execute,UpdatedUser,UpdatedTime) VALUES('" + id + "','" + taskEditorText[i].TaskSeverity + "','" + taskEditorText[i].TaskCategory + "','" + taskEditorText[i].TaskTitle + "','" + taskEditorText[i].TaskMessage + "','" + taskEditorText[i].TaskCode + "','" + taskEditorText[i].TaskName + "','" + true + "','" + CreatedUser + "','" + CreatedDate + "');");
}
Sample value which results in the syntax error
DROP TABLE CLIENT_VALIDATION.COMPANIES_INVAL_AVAILABILITY_DATE IF EXISTS;
CREATE TABLE CLIENT_VALIDATION.COMPANIES_INVAL_AVAILABILITY_DATE AS
(SELECT *
FROM CLIENT.COMPANIES
WHERE
AVAILABILITY_DATE != ''
AND
AVAILABILITY_DATE NOT LIKE '____-__-__');
I tried replacing the special characters, wrote regular expression, used Regex.Escape nothing worked for me. I don't have any control on the xml i parse. Even i am new to the H2Database. So if any knows a way to insert values of this type in to the column in the database can you please help me.
Here the database which we are using is H2DataBase ( Java database).
PreparedStatement prep = reader.Connection.prepareStatement("INSERT INTO " + Schema + ".DMTScriptTasks(DmtScriptId,TaskSeverity,TaskCategory,TaskTitle,TaskMessage,TaskCode,TaskName,Execute,UpdatedUser,UpdatedTime,SqlQuery) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
Then loop through the collection
for (int i = 0; i < taskEditorText.Count; i++)
{
prep.setString(1, id);
prep.setString(2, taskEditorText[i].TaskSeverity);
prep.setString(3, taskEditorText[i].TaskCategory);
prep.setString(4, taskEditorText[i].TaskTitle);
prep.setString(5, taskEditorText[i].TaskMessage);
prep.setString(6, taskEditorText[i].TaskCode);
prep.setString(7, taskEditorText[i].TaskName);
prep.setString(8, "true");
prep.setString(9, CreatedUser);
prep.setString(10, CreatedDate);
prep.setString(11, taskEditorText[i].SqlQuery);
//batch insert
prep.addBatch();
reader.Connection.setAutoCommit(false);
prep.executeBatch();
reader.Connection.setAutoCommit(true);
}
Here taskEditorText is a List and the database i am trying to insert values is H2Database.
Then I did batch update of the insert query.

Resources