Duplicated records in HQL - java

I need to return the ID of the duplicate records from a table using HQL. I Tried:
"select pro from FichaProcedimento pro "
+ " inner join ("
+ " select pro.ficha.id, proc.id, proc.regiaoDente, proc.face "
+ " from FichaProcedimento "
+ " group by pro.ficha.id, proc.id, proc.regiaoDente, proc.face"
+ " having count(*)>1) proc "
+ " on pro.procedimento.id = proc.procedimento.id "
+ " where pro.ficha.id=? "
Error occurred:
unexpected token: ( near line 1, column 100 [select pro from br.srv.datasolution.infodata.odontologico.entity.FichaProcedimento pro inner join ( select pro.ficha.id, proc.id, proc.regiaoDente, proc.face from br.srv.datasolution.infodata.odontologico.entity.FichaProcedimento group by pro.ficha.id, proc.id, proc.regiaoDente, proc.face having count(*)>1) proc on pro.procedimento.id = proc.procedimento.id where pro.ficha.id=? ]
How to solve?

Solved with native query. Thanks! Example:
delete from Tabela
where Nome in
(select Nome from Tabela
group by Nome
having Count(Nome)>1)
and not matricula in
(select Min(Matricula) from Tabela
group by Nome
having Count(Nome)>1)

Related

MySQL Deletion Query, Multiple Inner Joins

I want to delete an "order" from my database using the primary key, orderID. The orderID is a foreign key in orderItem, OrderItem has a foreign key in foodItem called foodItemID, foodItem has a foreign key in menu called menuID.
Below is my query:
"DELETE FROM orders, orderitem, fooditem, menu " +
"USING orders " +
"INNER JOIN orderitem " +
"WHERE orderID = " + "'" + orderID + "' " + " AND orders.orderID = orderItem.orderID " +
"INNER JOIN foodItem " +
"WHERE orderItem.foodItemID = foodItemID.foodItemID " +
"INNER JOIN Menu " +
"WHERE foodItem.menuID = menu.menuID";
I am coding in JAVAFX..
The error I receive is:
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN foodItem WHERE orderItem.foodItemID = foodItemID.foodItemID INNER JOI' at line 1
You don't join WHERE, you join ON something. So
"DELETE FROM orders, orderitem, fooditem, menu " +
"USING orders " +
"INNER JOIN orderitem " +
"ON orderID = " + "'" + orderID + "' " + " AND orders.orderID = orderItem.orderID " +
"INNER JOIN foodItem " +
"ON orderItem.foodItemID = foodItemID.foodItemID " +
"ON JOIN Menu " +
"ON foodItem.menuID = menu.menuID";
Also, this part
"ON orderID = " + "'" + orderID + "' " + "
Is a SQL Injection waiting to happen. You should use prepared statements instead. How you use them depends on what library/framework you're using to connect to the db (which you didn't specify).

Spring Data native query with params don't work

I have a native query like the following one:
#Query(value = "SELECT * FROM (" +
" SELECT result.*, ROWNUM rn FROM (" +
" SELECT tmp.* FROM (" +
" SELECT " +
" e.id, " +
" e.employee_number, " +
" d.name, " +
" d.surname " +
" FROM employee e INNER JOIN detail d ON e.id_detail = d.id " +
" WHERE e.status = :status " +
" ) tmp " +
" ORDER BY :sortColumn :sortDirection " +
" ) result " +
" WHERE ROWNUM <= (:pageIndex + :pageSize) " +
") " +
"WHERE rn > :pageIndex "
, nativeQuery = true)
ArrayList<Object> getEmployeeDetails( #Param("status") EmployeeStatus status,
#Param("pageSize") int pageSize,
#Param("pageIndex") int pageIndex,
#Param("sortDirection") String sortDirection,
#Param("sortColumn") String sortColumn);
and I'm getting the following errors:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
// ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
// ...
Caused by: java.sql.SQLSyntaxErrorException: ORA-01745: invalid host/bind variable name
What I tried is different return type (and didn't manage to find out which one to use eventually), inserting params with #Param() annotations.
The query itself does work - I tried it directly in the database, but I'm experiencing problems with handling it in Spring.
The query itself for easy debugging:
SELECT * FROM (
SELECT result.*, ROWNUM rn FROM (
SELECT tmp.* FROM (
SELECT
e.id,
e.employee_number,
d.name,
d.surname
FROM employee e INNER JOIN detail d ON e.id_detail = d.id
WHERE e.status = 'status'
) tmp
ORDER BY tmp.name desc
) result
WHERE ROWNUM <= (0 + 5)
)
WHERE rn > 0
EDIT:
I've updated the question with comment suggestions of removing all of the \n's and checking for missing whitespaces.
Plain query, without using any parameters also work, but as I start to insert parameters through #Param() annotations or binds (?1) it stops working giving the errors I updated above.
if EmployeeStatus is enum you have to use this in your query
WHERE e.status = :#{#status.name()}

Bad SQL grammar -The column name was not found in this ResultSet?

Hello I am using a JDBC query and I am having this error but I don't understand why, or what exactly is the meaning of this error and what is wrong with the query.
The query is as below
private List<StatisticsLog> runStatistics(Integer partnerId, LocalDate ldStart, LocalDateTime ldtEnd, String statType)
{
return jdbcTemplate.query("SELECT S.APP_ID, S.LOG_TYPE, ACC.CONTACT_PERSON_FIRST_NAME, ACC.CONTACT_PERSON_LAST_NAME, ACV.VERSION_APP_NAME, "
+ "'" + statType.trim() + "' STATTYPE, "
+ "ACV.APP_CATALOG_ID, ACV.APP_CATALOG_VERSION_ID, ACV.VERSION, ACV.UPDATED_AT, ACV.VERSION_LOGO_EXT, ACV.HAS_LOGO, "
+ "LANG.LANGUAGE_NAME_SHORT, LANG.LANGUAGE_ID , S.count, S.PARTNER_ID, APP.CREATED_AT "
+ "FROM (SELECT partner_id, log_type, app_id, language_id, count(*) as count FROM public.statistics_log "
+ " WHERE partner_id = ? "
+ " and logged_at between ? and ? "
+ "group by 1, log_type, app_id, language_id) as S "
+ "INNER JOIN APP_CATALOG_ACCOUNT ACP ON ACP.APP_CATALOG_SERIAL_ID = S.APP_ID "
+ "INNER JOIN APP_CATALOG APP ON APP.APP_CATALOG_SERIAL_ID = S.APP_ID "
+ "INNER JOIN ACCOUNT ACC ON ACC.ACCOUNT_ID = S.PARTNER_ID "
+ "INNER JOIN APP_CATALOG_VERSION ACV on ACV.APP_CATALOG_SERIAL_ID = APP.APP_CATALOG_SERIAL_ID AND ACV.STATUS = 3 "
+ "INNER JOIN LANGUAGE LANG ON LANG.LANGUAGE_ID = ACV.LANGUAGE_ID "
+ "ORDER BY S.count desc ",
new Object[] { partnerId, ldStart, ldtEnd }, new StatisticsLogRowMapper());
}
and I am getting the error from this column CREATED_AT that is part of the app catalog, and I think it should be there, also for more detailed also I will attach StatisticsLogRowMapper
public class StatisticsLogRowMapper implements RowMapper<StatisticsLog>
{
#Override
public StatisticsLog mapRow(ResultSet rs, int rowNum) throws SQLException
{
StatisticsLog stat = new StatisticsLog();
stat.setAppId(rs.getInt("APP_ID"));
stat.setPartnerId(rs.getInt("PARTNER_ID"));
stat.setCount(rs.getLong("COUNT"));
stat.setCreatedAt(rs.getTimestamp("CREATED_AT").toLocalDateTime());
stat.setPartnerFirstName(rs.getString("CONTACT_PERSON_FIRST_NAME"));
stat.setPartnerLastName(rs.getString("CONTACT_PERSON_LAST_NAME"));
stat.setAppNameDefault(rs.getString("VERSION_APP_NAME"));
stat.setAppCatalogId(rs.getInt("APP_CATALOG_ID"));
stat.setStatType(rs.getString("STATTYPE"));
stat.setLogType(LogTypeEnum.valueOf(rs.getString("LOG_TYPE").trim()));
stat.setAppCatalogVersionId(rs.getInt("APP_CATALOG_VERSION_ID"));
stat.setVersion(rs.getInt("VERSION"));
stat.setUpdatedAt(rs.getDate("UPDATED_AT"));
stat.setVersionLogoExt(rs.getString("VERSION_LOGO_EXT"));
stat.setHasLogo(rs.getBoolean("HAS_LOGO"));
stat.setLanguageNameShort(rs.getString("LANGUAGE_NAME_SHORT"));
stat.setLanguageId(rs.getInt("LANGUAGE_ID"));
return stat;
}
}
THE ERROR IS: "PreparedStatementCallback; bad SQL grammar [SELECT S.APP_ID, S.LOG_TYPE, ACC.CONTACT_PERSON_FIRST_NAME, ACC.CONTACT_PERSON_LAST_NAME, ACV.VERSION_APP_NAME, 'days30' STATTYPE, ACV.APP_CATALOG_ID, ACV.APP_CATALOG_VERSION_ID, ACV.VERSION, ACV.UPDATED_AT, ACV.VERSION_LOGO_EXT, ACV.HAS_LOGO, LANG.LANGUAGE_NAME_SHORT, S.count, S.PARTNER_ID FROM (SELECT partner_id, log_type, app_id, language_id, count(*) as count FROM public.statistics_log WHERE logged_at between ? and ? group by 1, log_type, app_id, language_id, partner_id) as S INNER JOIN APP_CATALOG_ACCOUNT ACP ON ACP.APP_CATALOG_SERIAL_ID = S.APP_ID INNER JOIN APP_CATALOG APP ON APP.APP_CATALOG_SERIAL_ID = S.APP_ID INNER JOIN ACCOUNT ACC ON ACC.ACCOUNT_ID = S.PARTNER_ID INNER JOIN APP_CATALOG_VERSION ACV on ACV.APP_CATALOG_SERIAL_ID = APP.APP_CATALOG_SERIAL_ID AND ACV.STATUS = 3 INNER JOIN LANGUAGE LANG ON LANG.LANGUAGE_ID = ACV.LANGUAGE_ID ORDER BY S.count desc ]; nested exception is org.postgresql.util.PSQLException: The column name CREATED_AT was not found in this ResultSet."
IN THE ERROR SEEMS THIS FIELD ISN'T THERE SOMEHOW
If you have any idea what may be wrong or thing I can try please don't hesitate to comment, I would appreciate d even the smallest help thank you.
I can see there is an error in line 2 of the query - + "'" + statType.trim() + "' STATTYPE, ", right after the quote. STATTYPE does not have a table reference and is appended with a string. That could be another issue. I cannot comment on the question as I dont have enough reputation.

Pageable in JPA native query

I want to use pagination with a native query. I use for this this syntaxe as in this example : Spring Data and Native Query with pagination
and it's my query:
#Query(value="SELECT rownum() as RN, users.num, users .l_service,service.type_service, users.date, " +
"chambre.price," +
"price* ( case when(datediff(day,date_d,date_f)=0) then 1 " +
"else datediff(day,date_d,date_f) end ) as Montant," +
"case when (service.type_service='R') and datediff(day,date_d,date_f) >=21 " +
"then (21300+(datediff(day,date_d,date_f)-21)*200)" +
"else price*(case when(datediff(day,date_d,date_f)=0) then 1 else datediff(day,date_d,date_f)end) end AS Montant_final " +
" users.year, users.Etat, " +
" from chambre JOIN users ON chambre.code = users.type " +
"JOIN service on service.code = users.l_service " +
" WHERE users.Etat='V' and RN between ?#{ #pageable.offset -1} and ?#{#pageable.offset + #pageable.pageSize order by users.num",
countQuery ="select count(*) from users ",nativeQuery = true)
Page<Object> getStatistiques(Pageable pageable);
I get this error :
Cannot mix JPA positional parameters and native Hibernate positional/ordinal parameters
This is the solution I found to my problem:
#Query(value="SELECT * from (SELECT ROW_NUMBER() OVER (ORDER BY users.num) as RN, users.num, users .l_service,service.type_service, users.date, " +
"chambre.price," +
"price* ( case when(datediff(day,date_d,date_f)=0) then 1 " +
"else datediff(day,date_d,date_f) end ) as Montant," +
"case when (service.type_service='R') and datediff(day,date_d,date_f) >=21 " +
"then (21300+(datediff(day,date_d,date_f)-21)*200)" +
"else price*(case when(datediff(day,date_d,date_f)=0) then 1 else datediff(day,date_d,date_f)end) end AS Montant_final " +
" users.year, users.Etat, " +
" from chambre JOIN users ON chambre.code = users.type " +
"JOIN service on service.code = users.l_service " +
" WHERE users.Etat='V') AS STA where RN between ?#{ #pageable.offset -1} and ?#{#pageable.offset + #pageable.pageSize} order by STA.num",
countQuery ="select count(*) from users ",nativeQuery = true)
Page<Object> getStatistiques(Pageable pageable);
I share it with you perhaps it can help someone else!

Named Query to SELECT rows with MAX(column name), DISTINCT by another column

I have a case similar to the one described in this question, I wrote an identical query which works, but when I try to write it as a jpql named query, I'm getting an error.
My query:
#NamedQuery(
name = "findRankingsBetween",
query = "SELECT rt FROM Rankingtable rt " +
"INNER JOIN " +
"(SELECT teamId, MAX(lastupdate) as MaxDateTime " +
"FROM Rankingtable " +
"GROUP BY teamId) grouped " +
"ON rt.teamId = grouped.teamId " +
"AND rt.lastupdate = grouped.MaxDateTime " +
"WHERE rt.lastupdate BETWEEN :from AND :to"
)
Error:
Error in named query: findRankingsBetween: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 79
How to write the query properly in jpql?
As noted in this answer, a subquery in JPQL can only occur in select and where clauses.
Hibernate doc.
An equivalent query in JPQL is:
"SELECT rt FROM Rankingtable rt " +
"WHERE rt.lastupdate = (SELECT MAX(r2.lastupdate) " +
"FROM Rankingtable r2 " +
"WHERE r2.teamid = rt.teamid) " +
"AND rt.lastupdate BETWEEN :from AND :to"

Categories