JPA Query gets error InvalidDataAccessResourceUsageException - spring-data-jpa

I've written a query
public interface TeabagRepository extends CrudRepository<Teabag, Long> {
#Query(value = "SELECT t.post, t.status, t.expires FROM teabags t WHERE t.status = 'hot' AND t.user_id = ?1", nativeQuery = true)
Teabag findTea(Long id);
}
I set spring.jpa.show-sql=true in application.properties
So the query is shown in the console, I ran this query in database and it works:
SELECT
t.post,
t.status,
t.expires
FROM
teabags t
WHERE
t.status = 'hot'
AND t.user_id = ?
The error:
2018-05-08 19:22:27.675 ERROR 1259 --- [nio-8080-exec-4]
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 execute query; SQL [SELECT t.post, t.status, t.expires
FROM teabags t WHERE t.status = 'hot' AND t.user_id = ?]; nested
exception is org.hibernate.exception.SQLGrammarException: could not
execute query] ****with root cause
org.postgresql.util.PSQLException: The column name id was not found in
this ResultSet.****
org.springframework.dao.InvalidDataAccessResourceUsageException: could
not execute query; SQL [SELECT t.post, t.status, t.expires FROM
teabags t WHERE t.status = 'hot' AND t.user_id = ?];
update: more error text
nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
root error
with root cause
org.postgresql.util.PSQLException: The column name id was not found in
this ResultSet.
Why isn't this query working in the spring boot application?

The result was expecting every column of the Teabag so I had to select t.*
#Query(value = "SELECT t.* FROM teabags t WHERE t.status = 'hot' AND t.user_id = ?1", nativeQuery = true)
Teabag findTea(Long id);

Related

Using $1 in the #Query throws exception: Cannot encode parameter of type org.springframework.r2dbc.core.Parameter

I'm using R2DBC in my project. After upgrading to Spring Boot from 2.5.* to 2.6.1 my query:
#Query("SELECT EXISTS(SELECT 1 FROM some_link links WHERE links.data_id = $1 AND links.some_id != links.source_id)")
fun existsByDataIdAndLocked(dataId: UUID): Mono<Boolean>
Throws an exception:
Suppressed: java.lang.IllegalArgumentException: Cannot encode parameter of type org.springframework.r2dbc.core.Parameter
at io.r2dbc.postgresql.codec.DefaultCodecs.encode(DefaultCodecs.java:192)
at io.r2dbc.postgresql.ExtendedQueryPostgresqlStatement.bind(ExtendedQueryPostgresqlStatement.java:89)
at io.r2dbc.postgresql.ExtendedQueryPostgresqlStatement.bind(ExtendedQueryPostgresqlStatement.java:47)
at org.springframework.r2dbc.core.DefaultDatabaseClient$StatementWrapper.bind(DefaultDatabaseClient.java:544)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at org.springframework.data.r2dbc.repository.query.StringBasedR2dbcQuery$ExpandedQuery.bindTo(StringBasedR2dbcQuery.java:227)
at org.springframework.r2dbc.core.DefaultDatabaseClient$DefaultGenericExecuteSpec.lambda$execute$2(DefaultDatabaseClient.java:334)
at org.springframework.r2dbc.core.DefaultDatabaseClient$DefaultGenericExecuteSpec.lambda$execute$3(DefaultDatabaseClient.java:374)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:46)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:31)
at org.springframework.r2dbc.core.DefaultFetchSpec.lambda$all$2(DefaultFetchSpec.java:88)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:46)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:31)
at org.springframework.r2dbc.core.DefaultDatabaseClient.lambda$inConnectionMany$6(DefaultDatabaseClient.java:138)
at reactor.core.publisher.FluxUsingWhen.deriveFluxFromResource(FluxUsingWhen.java:119)
at reactor.core.publisher.FluxUsingWhen.access$000(FluxUsingWhen.java:53)
at reactor.core.publisher.FluxUsingWhen$ResourceSubscriber.onNext(FluxUsingWhen.java:194)
... 172 more
Once I change $1 in the query to :dataId then it works.
Why is that? As per documentation, both are valid.

Query Native - could not extract ResultSet

i have a problem.I explain my situation: SpringBoot + Hibernate + Multitenant (DB master + DB for tenant) + Postgressql. I have two datasource configurations, one for the master and one for each client's database. I need doing a query native in JPARepository And that's the only way I can do it
In my JPARepository :
public interface IEntity extends JpaRepository<Entity, Integer> {
........
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying ///Add 1
#Transactional ///Add 2
void restarID();
}
when I first call the method, I got:
> Hibernate:
ALTER SEQUENCE entity_identity_seq RESTART
> 2019-09-10 15:41:53.919 WARN 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
> 2019-09-10 15:41:53.919 ERROR 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : La consulta no retornó ningún resultado.
> 2019-09-10 15:41:53.940 ERROR 18680 --- [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.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: La consulta no retornó ningún resultado.
After looking for solutions and discovered that he needed to add
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying
void restarID();
But the query is not made in hibernate and this error comes up:
> 2019-09-10 15:46:57.972 ERROR 14392 --- [nio-8080-exec-1] 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.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query] with root cause
javax.persistence.TransactionRequiredException: Executing an update/delete query
I keep searching and find that I should add #Transactional. Then :
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying
#Transactional
void restarID();
But, then come back, I call the method, I got:
> Hibernate:
ALTER SEQUENCE entity_identity_seq RESTART
> 2019-09-10 15:41:53.919 WARN 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
> 2019-09-10 15:41:53.919 ERROR 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : La consulta no retornó ningún resultado.
> 2019-09-10 15:41:53.940 ERROR 18680 --- [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.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: La consulta no retornó ningún resultado.
Please, will anyone have any recommendations?
I am new to hibernate. Thank you.
If someone yet have the same problem, I've resolved it, adding the next to the query:
#Modifying(clearAutomatically = true)
#Transactional

How to pass argument to JPA when using Postgres LTREE?

I have a Spring Boot app that is using JPA and a Postgres table with ltree data structure.
It works when I query using sql statement but not when I pass an argument.
Controller
#GetMapping("/path")
ResponseEntity<?> findAllByPath() {
List<Tree> allByPath = treeRepository.findAllByPath("A");
return ResponseEntity.ok().body(allByPath);
}
Working Code in Repository
#Query(value = "SELECT * FROM Tree WHERE path <# 'A'", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);
*Not Working Code in Repository
#Query(value = "SELECT * FROM Tree WHERE path <# '" + ":pathToSearch" +"'", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);
Error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jan 04 17:41:43 CET 2019
There was an unexpected error (type=Internal Server Error, status=500). could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Stacktrace
2019-01-04 17:41:43.357 DEBUG 33826 --- [nio-8080-exec-1] org.hibernate.SQL :
SELECT
*
FROM
Tree
WHERE
path <# ':pathToSearch'
Hibernate:
SELECT
*
FROM
Tree
WHERE
path <# ':pathToSearch'
2019-01-04 17:41:43.362 WARN 33826 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42601
2019-01-04 17:41:43.363 ERROR 33826 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: syntax error at position 0
Position: 34
2019-01-04 17:41:43.381 ERROR 33826 --- [nio-8080-exec-1] 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
org.postgresql.util.PSQLException: ERROR: syntax error at position 0
Position: 34
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
EDIT:
When I try removing the quotes in the Query, it fails with another error.
#Query(value = "SELECT * FROM Tree WHERE path <# :pathToSearch", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);
2019-01-08 12:52:25.213 DEBUG 18840 --- [nio-8080-exec-1] org.hibernate.SQL :
SELECT
*
FROM
Tree
WHERE
path <# ?
Hibernate:
SELECT
*
FROM
Tree
WHERE
path <# ?
2019-01-08 12:52:25.222 TRACE 18840 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [A]
2019-01-08 12:52:25.240 WARN 18840 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42883
2019-01-08 12:52:25.240 ERROR 18840 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: operator does not exist: ltree <# character varying
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 31
2019-01-08 12:52:25.266 ERROR 18840 --- [nio-8080-exec-1] 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
org.postgresql.util.PSQLException: ERROR: operator does not exist: ltree <# character varying
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 31
I fixed it by casting the parameter to ltree.
The modified method and query in the Repository is:
#Query(value = "SELECT * FROM Tree WHERE path <# CAST(:pathToSearch AS ltree)", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);

JPA access Postgresql 9.4 generated sequence "id" not exist error

I had a project needs to set up SMS gateway that works with JAVA-EE project. GAMMU 1.36.0 was selected.
backend DB is Postgresql 9.4, table inbox and sequence were created to hold in come SMS.
inbox created by use:
CREATE TABLE inbox (
"UpdatedInDB" timestamp(0) WITHOUT time zone NOT NULL DEFAULT LOCALTIMESTAMP(0),
"ReceivingDateTime" timestamp(0) WITHOUT time zone NOT NULL DEFAULT LOCALTIMESTAMP(0),
"Text" text NOT NULL,
"SenderNumber" varchar(20) NOT NULL DEFAULT '',
"Coding" varchar(255) NOT NULL DEFAULT 'Default_No_Compression',
"UDH" text NOT NULL,
"SMSCNumber" varchar(20) NOT NULL DEFAULT '',
"Class" integer NOT NULL DEFAULT '-1',
"TextDecoded" text NOT NULL DEFAULT '',
"ID" serial PRIMARY KEY,
"RecipientID" text NOT NULL,
"Processed" boolean NOT NULL DEFAULT 'false',
CHECK ("Coding" IN
('Default_No_Compression','Unicode_No_Compression','8bit','Default_Compression','Unicode_Compression')));
id is a sequence number hold in:
--CREATE SEQUENCE inbox_ID_seq;
table structure looks like:
smsd-> \d inbox
Table "public.inbox"
Column | Type | Modifiers
-------------------+--------------------------------+----------------------------------------------------------------
UpdatedInDB | timestamp(0) without time zone | not null default ('now'::text)::timestamp(0) without time zone
ReceivingDateTime | timestamp(0) without time zone | not null default ('now'::text)::timestamp(0) without time zone
Text | text | not null
SenderNumber | character varying(20) | not null default ''::character varying
Coding | character varying(255) | not null default 'Default_No_Compression'::character varying
UDH | text | not null
SMSCNumber | character varying(20) | not null default ''::character varying
Class | integer | not null default (-1)
TextDecoded | text | not null default ''::text
ID | integer | not null default nextval('"inbox_ID_seq"'::regclass)
RecipientID | text | not null
Processed | boolean | not null default false
Indexes:
"inbox_pkey" PRIMARY KEY, btree ("ID")
Check constraints:
"inbox_Coding_check" CHECK ("Coding"::text = ANY (ARRAY['Default_No_Compression'::character varying, 'Unicode_No_Compression'::character varying, '8bit'::character varying, 'Default_Compression'::character varying, 'Unicode_Compression'::character varying]::text[]))
Triggers:
update_timestamp BEFORE UPDATE ON inbox FOR EACH ROW EXECUTE PROCEDURE update_timestamp()
smsd->
Please note: column ids' position is 10 in the table.
This table is working well with GAMMU 1.36.0, send and receive SMS properly.
When I try to develop a EJB to bring the inbox information to my web application.
I am using JPA 2.1, implementation is EclipseLink 2.5.2. persistence.xml looks like:
<persistence-unit name="SmsdJPANBPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<mapping-file>com/longz/smsd/model/SmsdInboxEntity.xml</mapping-file>
<mapping-file>com/longz/smsd/model/SmsdOutboxEntity.xml</mapping-file>
<mapping-file>com/longz/smsd/model/SmsdSentitemsEntity.xml</mapping-file>
<class>com.longz.smsd.model.SmsdInboxEntity</class>
<class>com.longz.smsd.model.SmsdOutboxEntity</class>
<class>com.longz.smsd.model.SmsdSentitemsEntity</class>
<properties>
<property name="eclipselink.jdbc.url" value="jdbc:postgresql://10.0.1.100:5433/smsd"/>
<property name="eclipselink.jdbc.driver" value="org.postgresql.Driver"/>
<property name="eclipselink.jdbc.user" value="any"/>
<property name="eclipselink.jdbc.password" value="any"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
JPA entity bean defined:
#Entity
#Table(name = "inbox", schema = "public", catalog = "smsd")
#NamedQueries({
/*#NamedQuery(name = "Inbox.findAll", query = "SELECT i FROM InboxEntity i ORDER BY i.id DESC"),*/
#NamedQuery(name = "Inbox.findAll", query = "SELECT i FROM SmsdInboxEntity i order by i.id desc"),
......
public class SmsdInboxEntity implements Serializable{
......
#Id
#SequenceGenerator(name="JOB_MISFIRE_ID_GENERATOR", sequenceName="inbox_ID_seq",schema = "public", allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator="JOB_MISFIRE_ID_GENERATOR")
#Column(name = "ID", nullable = false, insertable = true, updatable = true)
public int getId() {
return id;
}
......
}
stateless session bean as:
#Remote(InboxEntityFacadeRemote.class)
#Stateless(mappedName= "inboxEntityFacadeEJB")
public class InboxEntityFacade extends AbstractFacade<SmsdInboxEntity> implements InboxEntityFacadeRemote {
#PersistenceContext(unitName = "SmsdJPANBPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public InboxEntityFacade() {
super(SmsdInboxEntity.class);
}
#Override
public List<SmsdInboxEntity> findAll(){
Query query = em.createNamedQuery("Inbox.findAll");
return new LinkedList<SmsdInboxEntity>(query.getResultList());
/*return super.findAll();*/
}
I tried to use findall() function to list all sms in inbox. This function will call named query statement:
#NamedQuery(name = "Inbox.findAll", query = "SELECT i FROM SmsdInboxEntity i order by i.id desc"),
Test EJB client as:
try {
Context context = new InitialContext(properties);
InboxEntityFacadeRemote inboxEnFaRemote = (InboxEntityFacadeRemote)context.lookup("inboxEntityFacadeEJB#com.longz.smsd.remote.InboxEntityFacadeRemote");
System.out.println("inboxEntityFacadeEJB found.");
List<com.longz.smsd.model.SmsdInboxEntity> todaysemails = inboxEnFaRemote.findAll();
System.out.println("Records found: "+ todaysemails.size());
todaysemails.stream().forEach((e) -> {
System.out.println(e.getTextDecoded());
});
}catch (NamingException e) {
e.printStackTrace();
}
}
Everything is work fine so far. but very strange error thrown:
run:
inboxEntityFacadeEJB found.
Exception in thread "main" javax.ejb.EJBException: EJB Exception: ; nested exception is:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
Error Code: 0
Call: SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC
Query: ReadAllQuery(name="Inbox.findAll" referenceClass=SmsdInboxEntity sql="SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC")
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.unwrapRemoteException(RemoteBusinessIntfProxy.java:117)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:92)
at com.sun.proxy.$Proxy0.findAll(Unknown Source)
at weblogicejbclient.WeblogicInboxEJBClient.main(WeblogicInboxEJBClient.java:38)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
Error Code: 0
Call: SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC
Query: ReadAllQuery(name="Inbox.findAll" referenceClass=SmsdInboxEntity sql="SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:378)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:469)
at com.longz.smsd.ejb.InboxEntityFacade.findAll(InboxEntityFacade.java:36)
at com.longz.smsd.ejb.InboxEntityFacadeEJB_s9wt3_InboxEntityFacadeRemoteImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:34)
at com.longz.smsd.ejb.InboxEntityFacadeEJB_s9wt3_InboxEntityFacadeRemoteImpl.findAll(Unknown Source)
at com.longz.smsd.ejb.InboxEntityFacadeEJB_s9wt3_InboxEntityFacadeRemoteImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:701)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:231)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:527)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:523)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
Error Code: 0
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:682)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:299)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2738)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2691)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:495)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1168)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1127)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:403)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1215)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1751)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
... 15 more
Caused by: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:1007)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:642)
... 35 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
seems PSQL trying find "id" column in position 8 instead of position 10 and actually "id" column located in position 10 in inbox table.
Any idea and advice please! Appreciated!!
Your problem is case-sensitivity: JPA works in case insensitive mode by default (i.e. it won't quote identifiers in its queries), while PostgreSQL will convert any unquoted identifiers to lower-case (this is the way PostgreSQL tries to achieve case insensitivity). But, you defined your "ID" column in case-sensitive mode (note the quotes).
An ugly workaround is, that you define your entity in a case-sensitive way:
#Column(name = "\"ID\"")
Or, you can define your table in a case-insensitive way (which is preferred):
CREATE TABLE inbox (
ID serial PRIMARY KEY
-- ...
);
Eventually. This issue was fixed by using native SQL query
Query query = em.createNativeQuery("Select * from inbox",com.longz.smsd.model.SmsdInboxEntity.class);
return new LinkedList<SmsdInboxEntity>(query.getResultList());
Seems JSQL is not 100% works in this situation.
This one will be help some one else who have the same issue.

CriteriaBuilder equal operator does not work

I am new to JPA. I am using EclipseLink 2.5.2 against Oracle database with Oracle JDBC driver. For the simple code below:
public List<DummyGrp> findByProperty(String propertyName, Object value) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<DummyGrp> cq = cb.createQuery(DummyGrp.class);
Root<DummyGrp> rootQuery = cq.from(DummyGrp.class);
cq.select(rootQuery);
cq.where(cb.equal(rootQuery.get(propertyName),value));
TypedQuery<DummyGrp> q = entityManager.createQuery(cq);
return q.getResultList();
}
The result is always empty. After turning on debug, I did see the SQL:
[EL Fine]: sql: 2015-01-09 12:20:51.215--ClientSession(559179052)--Connection(1008188683)--Thread(Thread[main,5,main])--SELECT ID, DATA_TYPE_IND, ENTRY_TYPE_IND, GRP_DESC, GRP_NAME, TRANS_ORIG_MM, TRANS_ORIG_YR FROM DUMMY_GRP WHERE (GRP_NAME = ?)
bind => [TG_dabfe8]
I debugged the Oracle JDBC. I was able to debug JDBC to the point that I can see the client side Oracle Statement with bind parameter and if I run the statement directly from an IDE, I can get result expected.
If I change the "equal" operator to "like" (see below):
cq.where(cb.like(rootQuery.get(propertyName),value+"%"));
I get result back.
I am sure I might be missing something simple. Can anyone enlighten me?
Thanks in advance,
Peter C.
By the way, here is the Oracle JDBC Diagnositcs log:
CONFIG: 5E158F33 SQL: SELECT ID, DATA_TYPE_IND, ENTRY_TYPE_IND, GRP_DESC, GRP_NAME, TRANS_ORIG_MM, TRANS_ORIG_YR FROM DUMMY_GRP WHERE (GRP_NAME = ?)
java.lang.Throwable: No Error
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1647)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4401)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4482)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:6272)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:1007)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:642)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:298)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:299)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2738)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2691)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:495)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1168)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1127)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:403)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1215)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1751)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:469)
at com.gaig.plentry.dao.DummyGroupDAOImpl.findByProperty(DummyGroupDAOImpl.java:47)
at com.gaig.plentry.dao.DummyGroupDAOImpl.findByGroupName(DummyGroupDAOImpl.java:28)
at com.gaig.plentry.dao.DummyGroupDAOImpl$$FastClassBySpringCGLIB$$2d2bc23e.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)