spring JPA Hibernate MariaDB - mysql

i am trying to connect to mariaDB v10.2.14 from my spring JPA hibernate application. i am using
driverClassName: com.mysql.jdbc.Driver
and
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
i have a query method to find the top first row, by using "findTop1" keywords... when the query is actually formed , it uses 'offset 0 rows fetch next 1 rows only' instead of LIMIT 0,1 ... because of this the maria DB server throws an error...
how can i change my driver / dialect file to form a query using LIMIT clause instead of offset-fetch..
note: i have tried all combinations of mariadbdialect and mariadb driverclass names like , org.hibernate.dialect.MariaDB53Dialect and org.mariadb.jdbc.Driver..
below is the exception i am getting
2018-06-27 11:31:19.936 INFO 10484 --- [nio-8080-exec-2] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select aboutpage0_.id as id1_0_, aboutpage0_.APPLICATION_NAME as APPLICAT2_0_, aboutpage0_.createdDate as createdD3_0_, aboutpage0_.effectiveDate as effectiv4_0_, aboutpage0_.LAST_UPD_TS as LAST_UPD5_0_, aboutpage0_.LAST_UPD_SYSUSR_ID as LAST_UPD6_0_, aboutpage0_.version as version7_0_ from XXXXX aboutpage0_ where aboutpage0_.APPLICATION_NAME=? and aboutpage0_.effectiveDate<=? order by aboutpage0_.LAST_UPD_TS desc, aboutpage0_.effectiveDate desc offset 0 rows fetch next ? rows only
2018-06-27 11:31:20.112 WARN 10484 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000
2018-06-27 11:31:20.112 ERROR 10484 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'offset 0 rows fetch next 1 rows only' at line 1
2018-06-27 11:31:20.142 ERROR 10484 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'offset 0 rows fetch next 1 rows only' at line 1

Prettyprinting the query:
select aboutpage0_.id as id1_0_, aboutpage0_.APPLICATION_NAME as APPLICAT2_0_,
aboutpage0_.createdDate as createdD3_0_, aboutpage0_.effectiveDate as effectiv4_0_,
aboutpage0_.LAST_UPD_TS as LAST_UPD5_0_, aboutpage0_.LAST_UPD_SYSUSR_ID as LAST_UPD6_0_,
aboutpage0_.version as version7_0_
from XXXXX aboutpage0_
where aboutpage0_.APPLICATION_NAME=?
and aboutpage0_.effectiveDate<=?
order by aboutpage0_.LAST_UPD_TS desc,
aboutpage0_.effectiveDate desc
offset 0 rows fetch next ? rows only 2018-06-27
should make it obvious that something went wrong in creating the SQL from Hibernate. It was probably headed for saying limit 1 offset 0, but failed. (Note: LIMIT comes before OFFSET.)

Related

Spring Boot throws an SQL Syntax exception

I am testing new endpoints on my API and getting an error that confuses me a bit.
2022-08-24 11:51:54.283 WARN 9836 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000
2022-08-24 11:51:54.283 ERROR 9836 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : 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 'WHERE) FROM rates WHERE (date BETWEEN '2022-01-01' AND '2022-03-01') AND ((null ' at line 1
2022-08-24 11:51:54.292 ERROR 9836 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/api/v1] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
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 'WHERE) FROM rates WHERE (date BETWEEN '2022-01-01' AND '2022-03-01') AND ((null ' at line 1
The confusing part for me is that I don't understand where it gets the first part of the query WHERE) in the error message.
Repo
#Query("SELECT * FROM rates WHERE (date BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR rate_code = :code) AND rate > 0)", nativeQuery = true)
fun getByDateRange(startDate: Date, endDate: Date, code: String?, pageable: Pageable): Page<RateEntity>
Controller
#GetMapping("/historic")
fun ratesForDateRange(
#RequestParam startDate: Optional<Date>,
#RequestParam endDate: Optional<Date>,
#RequestParam(required = false) code: String?,
#RequestParam(required = false) pageNumber: Int?
): Page<RateEntity> {
val lastDate = Date.valueOf(START_DATE)
val page = pageNumber ?: 0
println(code)
return repo.getByDateRange(
startDate.orElse(lastDate),
endDate.orElse(UtilFunctions.getCurrentSQLDate()),
code,
PageRequest.of(page, 50)
)
}
When I use the wrong code in request URL /api/v1/historic?startDate=2022-1-1&endDate=2022-3-1&code=abc I get an empty page as expected.
When I use the right code in request URL /api/v1/historic?startDate=2022-1-1&endDate=2022-3-1&code=suv and there are records between specified dates, I get the page with results as expected.
However, when I don't specify the code in request URL /api/v1/historic?startDate=2022-1-1&endDate=2022-3-1 I get this exception.
I use MySQL for Database and if use this query directly in CLI it works as expected.
For example this query
SELECT * FROM rates WHERE (date BETWEEN '2022-01-01' AND '2022-03-01') AND ((null IS NULL OR rate_code = null) AND rate > 0);
returns all results for specified date range as expected.
I think it is the problem with date_and_time in spring boot.
You are comparing two dates whereas the actual values saved are dateAndTime, which spring can not compare. Therefore, you should cast the date field as follow:
CAST(date as DATE)
Complete Query:
#Query("SELECT * FROM rates WHERE (CAST(date as DATE) BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR rate_code = :code) AND rate > 0)", nativeQuery = true)
Ok so I've already found where the problem lies and fixed it. Probably posted too soon.
After some more testing I found out that the exception occurs when amount of results is >= page size (50 in my case).
So after displaying hibernate queries with:
spring.jpa.show-sql = true
I found this:
Hibernate: SELECT count(WHERE) FROM rates WHERE (date BETWEEN ? AND ?) AND ((? IS NULL OR rate_code = ?) AND rate > 0)
That's where WHERE) comes from, which is obviously a syntax error.
The fix was to add custom count query like this:
#Query(
value = "SELECT * FROM rates WHERE (date BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR currency_code = :code) AND rate > 0)",
countQuery = "SELECT count(*) FROM rates WHERE (date BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR currency_code = :code) AND rate > 0)",
nativeQuery = true
)
fun getByDateRange(startDate: Date, endDate: Date, code: String?, pageable: Pageable): Page<RateEntity>

Getting 'Subquery returns more than 1 row' when updating a row - MariaDB

I got an error
SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more
than 1 row (SQL: update submissions set status = 2, updated_at =
'2020-11-11 09:02:27' where id = 85213835).
I'm using Eloquent ORM 5.7 and the the code is looks like this
$builder->update([
'status' => $request->getParam('new_status'),
'rejection_message' => $request->getParam('rejection_message') ? $request->getParam('rejection_message') : ""
]);
Previously the code was running well and just got this error recently.

PHP query works in localhost but breaks on live server

As the title suggests, I have a query that works fine in localhost but on my live environment I get a 500 server error. My PHP version locally is 7.4 but the live server uses 7.3.
The error I get is
PHP Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation:
1064 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 '(partition by prop_slug order by
prop_client) as rn
FROM listing_details
JOI' at line 4 in /hermes/bosnaweb23a/b60/ipg.site/site/index.php:23
Stack trace:
#0 /hermes/bosnaweb23a/b60/ipg.site/site/index.php(23): PDOStatement->execute()
#1 {m
My query looks like the below, but as I said this works fine in the local environment.
$get_listings = $db->prepare('SELECT *
FROM (
SELECT *,
row_number() over(partition by prop_slug order by prop_client) as rn
FROM listing_details
JOIN prop_gallery
ON prop_gallery.prop_gallery_id = listing_details.prop_slug
WHERE prop_slug LIKE prop_gallery_id OR prop_gallery_id LIKE prop_slug
AND listing_details.prop_mandate = 1
) x
where rn = 1');
$get_listings->execute();
$listings = $get_listings->fetchAll();
if (!$listings) {
echo 'Error: No Listings.';
}

Raw Sub Query inside selectRaw

BowlerMaster::selectRaw("
tour_id, bowler_id, bowler_name, ball_team,
SUM(balls) AS balls,
SUM(overs) AS overs,
DB::raw('SELECT runs, wicket FROM bowler_master WHERE tour_id = ".$request->tour_id." AND bowler_id = ".$request->player_id." ORDER BY wicket DESC, runs LIMIT 1 AS bbi')
")
->where($where_array)
->groupby(['tour_id','bowler_id'])
->get()->first();
In the above Eloquent Query I want to use raw query or any other wayout for getting the result of the raw query to get the value of bbi, but I am getting the following error :
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '::raw('SELECT match_id, runs, wicket FROM bowler_master WHERE tour_id = 1 AND bo' at line 25.
I am writing writing this query for generating following output,
{
"status": 200,
"message": "Success",
"bowler": {
"tour_id": 1,
"bowler_id": 21,
"bowler_name": "Kaushal Chauhan",
"ball_team": null,
"balls": "29",
"overs": 4.5,
"bbi": 9/3,
}
}
Uptil overs calculation, everything is working fine. I am not getting how to get the "bbi" key:value
Note: The result of the query will be pushed in response array and will be converted into json to get the output shown above.
Please guide.
Try this
BowlerMaster::selectRaw("tour_id, bowler_id, bowler_name, ball_team, SUM(balls) AS balls,SUM(overs) AS overs")
->selectSub("
SELECT runs
FROM bowler_master
WHERE tour_id = ".$request->tour_id."
AND bowler_id = ".$request->player_id."
ORDER BY wicket DESC, runs LIMIT 1
","runs")
->selectSub("
SELECT wicket
FROM bowler_master
WHERE tour_id = ".$request->tour_id."
AND bowler_id = ".$request->player_id."
ORDER BY wicket DESC, runs LIMIT 1
","wicket")
->where($where_array)
->groupby(['tour_id','bowler_id'])
->get()->first();
The rules of writing select sub query in laravel is as follows:
DB::table('tablename')
->select('column name','..')
->selectSub("Your full query","alias name")
->get()

symfony 3 doctrine porting data from mysql to postgres

I have a website build with Symfony3 and MySQL.
Now I must migrate from MySQL to Postgres for specials needs.
I've found this tool for migrate it automatically (nmig), and all it was all done, no problem found! YEAH!
I've changed my app/config/parameters.yml as symfony documentation tells.
Cache cleared!
But when I try to execute a simple query from symfony form index, I get this error:
An exception occurred while executing
SELECT DISTINCT id_0, MIN(sclr_25) AS dctrn_minrownum
FROM (
SELECT c0_.ID AS id_0,
c0_.RAG_SOCIALE AS rag_sociale_1,
c0_.INDIRIZZO AS indirizzo_2,
c0_.CIVICO AS civico_3,
c0_.CITTA AS citta_4,
c0_.PROVINCIA AS provincia_5,
c0_.NAZIONE AS nazione_6,
c0_.SETTORE AS settore_7,
c0_.REFERENTE1 AS referente1_8,
c0_.REFERENTE2 AS referente2_9,
c0_.CAP AS cap_10,
c0_.EMAIL1 AS email1_11,
c0_.EMAIL2 AS email2_12,
c0_.PIVA AS piva_13,
c0_.PATHLOGO AS pathlogo_14,
c0_.TELEFONO AS telefono_15,
c0_.NOTE AS note_16,
c0_.VALORE_OFFERTE_TOTALI AS valore_offerte_totali_17,
c0_.VALORE_OFF_ORD_ATTIVE AS valore_off_ord_attive_18,
c0_.VALORE_FATTURE_TOTALI AS valore_fatture_totali_19,
c0_.BANCA_APPOGGIO AS banca_appoggio_20,
c0_.CONDIZIONI_PAGAMENTO AS condizioni_pagamento_21,
c0_.RELATIVEID AS relativeid_22,
c0_.created_at AS created_at_23,
c0_.updated_at AS updated_at_24,
ROW_NUMBER() OVER(ORDER BY c0_.ID DESC) AS sclr_25
FROM clienti c0_
) dctrn_result
GROUP BY id_0
ORDER BY dctrn_minrownum ASC
LIMIT 10
OFFSET 0
**SQLSTATE[42703]: Undefined column: 7 ERRORE: la colonna c0_.id non esiste
LINE 1: ...d_0, MIN(sclr_25) AS dctrn_minrownum FROM (SELECT c0_.ID AS ...
^
500 Internal Server Error - InvalidFieldNameException**
Same error if I try this query into sqleditor: same error!
What's wrong on my configuration??
Thx