PSQLException: The column name clazz_ was not found in this ResultSet - postgresql

I am trying to fetch a PlaceEntity. I've previously stored a bunch of GooglePlaceEntity objects where
#Entity
#Table(name = "place")
#Inheritance(
strategy = InheritanceType.JOINED
)
public class PlaceEntity extends AbstractTimestampEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
and
#Entity
#Table(name = "google_place")
public class GooglePlaceEntity extends PlaceEntity {
// Additional fields ..
}
However, neither do I want to send information stored in google_place nor do I want to load it unnecessarily. For this reason I am only fetching
public interface PlaceRepository extends JpaRepository<PlaceEntity, Long> {
#Query(value = "" +
"SELECT * " +
"FROM place " +
"WHERE earth_distance( " +
" ll_to_earth(place.latitude, place.longitude), " +
" ll_to_earth(:latitude, :longitude) " +
") < :radius",
nativeQuery = true)
List<PlaceEntity> findNearby(#Param("latitude") Float latitude,
#Param("longitude") Float longitude,
#Param("radius") Integer radius);
}
and what I get is this:
org.postgresql.util.PSQLException: The column name clazz_ was not found in this ResultSet.
at org.postgresql.jdbc.PgResultSet.findColumn(PgResultSet.java:2588) ~[postgresql-9.4.1208-jdbc42-atlassian-hosted.jar:9.4.1208]
at org.postgresql.jdbc.PgResultSet.getInt(PgResultSet.java:2481) ~[postgresql-9.4.1208-jdbc42-atlassian-hosted.jar:9.4.1208]
at com.zaxxer.hikari.pool.HikariProxyResultSet.getInt(HikariProxyResultSet.java) ~[HikariCP-2.7.8.jar:na]
at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$2.doExtract(IntegerTypeDescriptor.java:62) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
...
I am able to run this statement in pure PostgreSQL:
SELECT * FROM place WHERE
earth_distance(
ll_to_earth(place.latitude, place.longitude),
ll_to_earth(17.2592522, 25.0632745)
) < 1500;
but not using the JpaRepository.
And by the way, fetching a GooglePlaceEntity is working however:
#Query(value = "" +
"SELECT * " +
"FROM place JOIN google_place ON google_place.id = place.id " +
"WHERE earth_distance( " +
" ll_to_earth(place.latitude, place.longitude), " +
" ll_to_earth(:latitude, :longitude) " +
") < :radius",
nativeQuery = true)
List<GooglePlaceEntity> findNearby(#Param("latitude") Float latitude,
#Param("longitude") Float longitude,
#Param("radius") Integer radius);

In case of #Inheritance(strategy = InheritanceType.JOINED), when you retrieve data without nativeQuery=True in JPA repository, Hibernate will execute SQL like the following:
SELECT
table0_.id as id1_1_,
table0_.column2 as column2_2_1_,
... (main_table cols)
table0_1_.column1 as column1_1_0_,
... (table1 to N-1 cols)
table0_N_.column1 as column1_1_9_,
... (tableN-th cols)
CASE WHEN table0_1_.id is not null then 1
... (table1 to N-1 cols)
WHEN table0_N_.id is not null then N
WHEN table0_.id is not null then 0
END as clazz_
FROM table table0_
left outer join table1 table0_1_ on table0_.id=table0_1_.id
... (other tables join)
left outer join table2 table0_N_ on table0_.id=table0_N_.id
From the above SQL you can see clazz specification. If you want to map ResultSet to your super instance (PlaceEntity), you should specify clazz_ column in SELECT by yourself.
In your case it will be:
#Query(value = "" +
"SELECT *, 0 AS clazz_ " +
"FROM place " +
"WHERE earth_distance( " +
" ll_to_earth(place.latitude, place.longitude), " +
" ll_to_earth(:latitude, :longitude) " +
") < :radius",
nativeQuery = true)

You should use the name of the class instead of the table name on the query. Change place to PlaceEntity.
#Query(value = "" +
"SELECT * " +
"FROM place JOIN google_place ON google_place.id = place.id " +
"WHERE earth_distance( " +
" ll_to_earth(place.latitude, place.longitude), " +
" ll_to_earth(:latitude, :longitude) " +
") < :radius",
nativeQuery = true)
List<GooglePlaceEntity> findNearby(#Param("latitude") Float latitude,
#Param("longitude") Float longitude,
#Param("radius") Integer radius);

Related

JPQL: How to rewrite postgres native query to JPQL query that uses filter keyword

Im trying to avoid using native query. I have this query that uses the filter function, how could I rewrite this to not use that and work in regular jpql?
#Query(
"SELECT time_bucket(make_interval(:intervalType), d.time) as groupedDate, " +
"CAST(d.team_Id as varchar) as teamId, CAST(d.service_Id as varchar) as serviceId, CAST(d.work_id as varchar) as workId, " +
"ROUND(CAST(count(d.value) filter ( where d.type = 'A') AS numeric) /" +
" (CAST(count(d.value) filter ( where d.type = 'B') AS numeric)), 4) as total " +
"FROM datapoint d " +
"WHERE d.team_Id = :teamId and d.service_id in :serviceIds and d.work_id = :workspaceId and d.type in ('A', 'B') " +
"AND d.time > :startDate " +
"GROUP BY groupedDate, d.team_Id, d.service_Id, d.workspace_Id " +
"ORDER BY groupedDate DESC",
nativeQuery = true
)
in the FROM statement you have to use the DAO object instead of the table name

How to use android SQLITE SELECT with two parameters?

This code return empty cursor.What is wrong here?
Data is already there in sqlitedb.
public static final String COL_2 = "ID";
public static final String COL_3 = "TYPE";
public Cursor checkData(String id, String type){
SQLiteDatabase db = getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = " + id+ " AND " + COL_3 + " = " + type , null);
return res;
}
When you pass strings as parameters you must quote them inside the sql statement.
But by concatenating quoted string values in the sql code your code is unsafe.
The recommended way to do it is with ? placeholders:
public Cursor checkData(String id, String type){
SQLiteDatabase db = getWritableDatabase();
String sql = "SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = ? AND " + COL_3 + " = ?";
Cursor res = db.rawQuery(sql , new String[] {id, type});
return res;
}
The parameters id and type are passed as a string array in the 2nd argument of rawQuery().
I finally solved it.
public Cursor checkData(String id, String type){
SQLiteDatabase db = getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = '" + id+ "' AND " + COL_3 + " = '" + type +"'" , null);
return res;
}
if COL_3 type is string try this:
Cursor res = db.rawQuery("SELECT * FROM "+ TABLE_NAME + " WHERE " + COL_2 + " = " + id+ " AND " + COL_3 + " = '" + type + "'" , null);

Syntax error when querying results directly to a DTO

My native query -
interface PodcastRepository: JpaRepository<Podcast, Long> {
#Query(value = "SELECT new com.krtkush.sample.modules.podcast.models.PodcastDTO" +
"(p.id, p.author, p.title, p.description c.name, c2.name) " +
"AS sub_category_name FROM podcasts p " +
"LEFT JOIN categories c ON p.podcast_category_id = c.category_id " +
"LEFT JOIN categories c2 ON p.podcast_subcategory_id = c2.category_id " +
"WHERE p.podcast_owner = :ownerId", nativeQuery = true)
fun getPodcastsByOwner(#Param("ownerId")owner: Long): List<PodcastDTO>
}
However, when I execute the function I get the following error -
org.postgresql.util.PSQLException: ERROR: syntax error at or near "." Position: 15
position 15 is . after SELECT new com
I'm following this tutorial - https://smarterco.de/spring-data-jpa-query-result-to-dto/
The difference is that I'm using SQL rather than JPQL.

Spring Data JPA JSONB Paramaterization

What is the correct syntax (JPA, Spring Data, or SpEL) to convert this query into a Spring Data Repository nativeQuery?
SELECT *
FROM mytable
WHERE f_jsonb_arr_lower(myjsonb -> 'myArray', 'subItem', 'email')
#> '"foo#foo.com"';
I want to use an input parameter instead of hard-coding "foo#foo.com".
My model: Postgres myTable with a JSONB column myJsonb:
{
"myArray": [
{
"subItem": {
"email": "bar#bar.com"
}
},
{
"subItem": {
"email": "foo#foo.com"
}
}
]
}
Index described here.
The hard-coded version works:
#Query(value =
"SELECT m.* " +
" FROM mytable AS m " +
" WHERE f_jsonb_arr_lower(myjsonb -> 'myArray' ,'subItem', 'email') " +
" #> '\"foo#foo.com\"' " +
" ORDER BY ?#{#pageable} ",
// Spring Data nativeQueries with Pageable require a separate countQuery:
countQuery =
"SELECT count(m.id) " +
" FROM mytable AS m " +
" WHERE f_jsonb_arr_lower(myjsonb -> 'myArray' ,'subItem', 'email') " +
" #> '\"foo#foo.com\"' ",
nativeQuery = true)
Page<MyTableEntity> findAllHardcodedPageable(Pageable pageable);
But trying to leverage the lowercaseEmailAddress parameter in a Spring Data repository nativeQuery does not work:
#Query(value =
"SELECT m.* " +
" FROM mytable AS m " +
" WHERE f_jsonb_arr_lower(myjsonb -> 'myArray' ,'subItem', 'email') " +
" #> '\"?{lowercaseEmailAddress}\"' " +
" ORDER BY ?#{#pageable} ",
countQuery =
"SELECT count(m.id) " +
" FROM mytable AS m " +
" WHERE f_jsonb_arr_lower(myjsonb -> 'myArray' ,'subItem', 'email') " +
" #> '\"?{lowercaseEmailAddress}\"' ",
nativeQuery = true)
Page<MyTableEntity> findAllByEmailPageable
(String lowercaseEmailAddress, Pageable pageable);
In my Postgres query logging, I can see that the lowercaseEmailAddress parameter is never set:
LOG: execute S_2: COMMIT
LOG: execute S_3: BEGIN
LOG: execute <unnamed>: SELECT count(m.id) FROM mytable
AS m WHERE f_jsonb_arr_lower(myjsonb -> 'myArray',
'subitem', 'email') #> '"?1"'
LOG: execute S_11: ROLLBACK
Found the answer:
1) Pass only a double-quoted String to the spring data repository method:
String emailAddressWithDoubleQuotes = String.format("\"%s\"",emailAddress);
result = repository.findAllByEmailPageable(emailAddressWithDoubleQuotes, pageRequest).getContent();
2) The Spring Repository #Query needs to have the SpEL expression in parenthesis and be casted to jsonb:
static final String FIND_ALL_BY_EMAIL_QUERY = " FROM mytable AS m " +
" WHERE f_jsonb_arr_lower(metadata -> 'myArray', 'subItem', 'email') " +
" #> ( ?#{#lowercaseEmailAddress} )\\:\\:jsonb";
#Query( // only use 'ORDER BY #pageableWithNativeSort' on 'value' query:
value = "SELECT m.* " + FIND_ALL_BY_EMAIL_QUERY + " ORDER BY ?#{#pageableWithNativeSort} ",
// Spring Data nativeQueries with Pageable require a separate 'countQuery':
countQuery = "SELECT count(m.id) " + FIND_ALL_BY_EMAIL_QUERY,
nativeQuery = true)
Page<OrderEntity> findAllBysubItemEmail(
#Param("lowercaseEmailAddress") String lowercaseEmailAddress,
#Param("pageableWithNativeSort") Pageable pageableWithNativeSort);

An identification variable must be provided for a range variable declaration

I'm trying to use this query in my jpa but it doesn't work:
List<Object[]> query = em.createQuery("SELECT Tstat.idStatistiques, TL.codeLieu, TL.materiel, TL.zone, sum(Tstat.colis) as colis, Tstat.defaut, sum(Tstat.nbreDefaut) as nbreDefaut,"
+ " sum(Tstat.nonLu) as nonLu, sum(Tstat.multiple) as multiple, sum(Tstat.nonRecu) as nonRecu, sum(Tstat.incoherent) as incoherent, sum(Tstat.requete) as requete , "
+ "sum(Tstat.tempsFonctionnement) as tempsFonctionnement, SUM(Tstat.tempsUtilisation) as tempsUtilisation, Tstat.modeFonctionnement FROM "
+ "( SELECT CURRENT_DATE as horodatage, St.idStatistiques, St.colis, St.defaut, St.nbreDefaut, St.nonLu, St.requete, St.multiple, St.nonRecu, St.incoherent, St.tempsFonctionnement, St.tempsUtilisation, St.modeFonctionnement FROM Statistique St )"
+ " UNION "
+ "(SELECT h.horodatage, h.idStatistiques, h.colis, h.defaut, h.nbreDefaut, h.nonLu, h.nonRecu, h.requete, h.multiple, h.incoherent, h.tempsFonctionnement, h.tempsUtilisation, h.modeFonctionnement FROM Statistiqueshisto h )"
+ " Tstat "
+ "LEFT JOIN (SELECT * FROM Lieux) as TL on Tstat.idStatistiques = TL.code_VI WHERE idStatistiques like :A ").setParameter("A", 0040+"%").getResultList();
This gives me error
The expression is invalid, which means it does not follow the JPQL
grammar.