I am using Hibernate 6 with Amazons opensearch server in production. When i'm testing locally i don't want to use the opensearch server, instead i want to use local-filesystem to store the index files.
However i can't hibernate search to use local-filesystem even when i explicitly set it with jpaProperties.put("hibernate.search.backend.directory.type", "local-filesystem"); while at the same time not setting the property hibernate.search.backend.uris. Before all the hibernate search properties can be programmatically set i get the following error on startup:
default backend:
failures:
- HSEARCH400080: Unable to detect the Elasticsearch version running on the cluster: HSEARCH400007: Elasticsearch request failed: Connection refused: no further information
Request: GET with parameters {}
I have the following maven dependencies:
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-mapper-orm</artifactId>
<version>6.1.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-backend-elasticsearch-aws</artifactId>
<version>6.1.5.Final</version>
</dependency>
The following sets hibernate search and the lucene file destination path if using lucene only:
private Properties initializeJpaProperties() {
String luceneAbsoluteFilePath = useExternalElasticSearchServer ? null : setDefaultLuceneIndexBaseFilePath(); //Alleen relevant wanneer je geen elastic search gebruikt.
Properties jpaProperties = new Properties();
//---------------------------open search aws related-----------------------------------
if(useExternalElasticSearchServer) {
jpaProperties.put("hibernate.search.backend.aws.credentials.type", "static");
jpaProperties.put("hibernate.search.backend.aws.credentials.access_key_id", awsId);
jpaProperties.put("hibernate.search.backend.aws.credentials.secret_access_key", awsKey);
jpaProperties.put("hibernate.search.backend.aws.region", openSearchAwsInstanceRegion);
jpaProperties.put("hibernate.search.backend.aws.signing.enabled", true);
jpaProperties.put("hibernate.search.backend.uris", elasticSearchHostAddress);
}
//--------------------------------------------------------------------------------------------
jpaProperties.put("hibernate.search.automatic_indexing.synchronization.strategy", indexSynchronizationStrategy);
jpaProperties.put("hibernate.search.backend.request_timeout", requestTimeout);
jpaProperties.put("hibernate.search.backend.connection_timeout", elasticSearchConnectionTimeout);
jpaProperties.put("hibernate.search.backend.read_timeout", readTimeout);
jpaProperties.put("hibernate.search.backend.max_connections", maximumElasticSearchConnections);
jpaProperties.put("hibernate.search.backend.max_connections_per_route", maximumElasticSearchConnectionsPerRout);
// jpaProperties.put("hibernate.search.schema_management.strategy", schemaManagementStrategy);
jpaProperties.put("hibernate.search.backend.thread_pool.size", maxPoolSize);
jpaProperties.put("hibernate.search.backend.analysis.configurer", "class:config.EnhancedLuceneAnalysisConfig");
// jpaProperties.put("hibernate.search.backend.username", hibernateSearchUsername); //Alleen voor wanneer je elastic search lokaal draait
// jpaProperties.put("hibernate.search.backend.password", hibernateSearchPassword);
if(!useExternalElasticSearchServer) {
jpaProperties.put("hibernate.search.backend.directory.type", "local-filesystem");
jpaProperties.put("hibernate.search.backend.directory.root", luceneAbsoluteFilePath);
jpaProperties.put("hibernate.search.backend.lucene_version", "LUCENE_CURRENT");
jpaProperties.put("hibernate.search.backend.io.writer.infostream", true);
}
jpaProperties.put("hibernate.jdbc.batch_size", defaultBatchSize);
jpaProperties.put("spring.jpa.properties.hibernate.jdbc.batch_size", defaultBatchSize);
jpaProperties.put("hibernate.order_inserts", "true");
jpaProperties.put("hibernate.order_updates", "true");
jpaProperties.put("hibernate.batch_versioned_data", "true");
// log.info("The directory of the lucene index files is set to {}", luceneAbsoluteFilePath);
return jpaProperties;
}
private String setDefaultLuceneIndexBaseFilePath() {
String luceneRelativeFilePath = ServiceUtil.getOperatingSystemCompatiblePath("/data/lucene/indexes/default");
StringBuilder luceneAbsoluteFilePath = new StringBuilder(System.getProperty("user.dir"));
if(!StringUtils.isEmpty(luceneIndexBase)) {
luceneRelativeFilePath = ServiceUtil.getOperatingSystemCompatiblePath(luceneIndexBase);
String OSPathSeparator = ServiceUtil.getOperatingSystemFileSeparator();
if(luceneRelativeFilePath.toCharArray()[0] != OSPathSeparator.charAt(0))
luceneAbsoluteFilePath.append(OSPathSeparator);
luceneAbsoluteFilePath.append(luceneRelativeFilePath);
validateUserDefinedAbsolutePath(luceneRelativeFilePath);
}
else{
log.warn("No relative path value for property 'lucene-index-base' was found in application.properties, will use the default path '{}' instead.", luceneRelativeFilePath);
luceneAbsoluteFilePath.append(luceneRelativeFilePath);
}
return luceneAbsoluteFilePath.toString();
}
I know that i can disable hibernate search completely with hibernate.search.enabled set to false but i don't want that. I want to be able to switch to lucene only without having to remove all the ElasticSearch/OpenSearch dependencies from my POM.xml beforehand. How do i do this?
EDIT: I just found out that you can set the backend type with hibernate.search.backend.type. This setting is set to the value elasticsearch by default. I should also be able to set this value to lucene but when i do that i get the following error:
default backend:
failures:
- HSEARCH000501: Invalid value for configuration property 'hibernate.search.backend.type': 'lucene'. HSEARCH000579: Unable to resolve bean reference to type 'org.hibernate.search.engine.backend.spi.BackendFactory' and name 'lucene'. Failed to resolve bean from Hibernate Search's internal registry with exception: HSEARCH000578: No beans defined for type 'org.hibernate.search.engine.backend.spi.BackendFactory' and name 'lucene' in Hibernate Search's internal registry. Failed to resolve bean from bean manager with exception: HSEARCH000590: No configured bean manager. Failed to resolve bean from bean manager with exception: HSEARCH000591: Unable to resolve 'lucene' to a class extending 'org.hibernate.search.engine.backend.spi.BackendFactory': HSEARCH000530: Unable to load class 'lucene': Could not load requested class : lucene Failed to resolve bean using reflection with exception: HSEARCH000591: Unable to resolve 'lucene' to a class extending
'org.hibernate.search.engine.backend.spi.BackendFactory': HSEARCH000530: Unable to load class 'lucene': Could not load requested class : lucene
EDIT 2:
I tried the setting the following settings with no success as well.
jpaProperties.put("hibernate.search.default_backend", "lucene");
jpaProperties.put("hibernate.search.backends.lucene.type", "lucene");
jpaProperties.put("hibernate.search.backend.type", "lucene");
You need to set the backend type explicitly according to the environment:
jpaProperties.put("hibernate.search.backend.type", isProductionEnvironment() ? "elasticsearch" : "lucene");
And you also need to have the Lucene backend in your classpath:
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-backend-lucene</artifactId>
<version>${my-hibernate-search-version}</version>
</dependency>
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.
Following the Getting Started with R2DBC video, I convert some of the repositories to reactive in an existing Spring Boot application with PostgreSQL as the database. The application works before the conversion. After I try to start up the application, I get the following error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'albumReactResource' defined in file [/app/classes/com/mycompany/myapp/web/rest/react/AlbumReactResource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'albumReactRepository' defined in class path resource [com/mycompany/myapp/config/ReactDatabaseConfig.class]: Unsatisfied dependency expressed through method 'albumReactRepository' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'r2dbcRepositoryFactory' defined in class path resource [com/mycompany/myapp/config/ReactDatabaseConfig.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.data.r2dbc.repository.support.R2dbcRepositoryFactory] from ClassLoader [sun.misc.Launcher$AppClassLoader#4e0e2f2a]
...
gallery-app_1 | Caused by: java.lang.ClassNotFoundException: org.springframework.data.repository.query.QueryMethodEvaluationContextProvider
gallery-app_1 | at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
gallery-app_1 | at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
gallery-app_1 | at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
gallery-app_1 | at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
gallery-app_1 | ... 51 common frames omitted
The QueryMethodEvaluationContextProvider class should be there. I guess that the database configuration can't co-exist with the existing database and Spring Data configuration.
The Spring Boot version is 2.0.5.RELEASE. And related dependencies are the followings:
compile "org.springframework.boot:spring-boot-starter-webflux"
compile "org.springframework.data:spring-data-jdbc:1.0.0.r2dbc-SNAPSHOT"
compile "io.r2dbc:r2dbc-postgresql:1.0.0.M5"
Here is the database configuration which is the same as the code for the video:
Configuration
public class ReactDatabaseConfig {
#Bean
PostgresqlConnectionFactory connectionFactory(){
return new PostgresqlConnectionFactory(
PostgresqlConnectionConfiguration.builder()
.host("localhost")
.database("gallery")
.username("postgres")
.password("")
.build()
);
}
#Bean
DatabaseClient databaseClient(ConnectionFactory connectionFactory){
return DatabaseClient.builder()
.connectionFactory(connectionFactory)
.build();
}
#Bean
R2dbcRepositoryFactory r2dbcRepositoryFactory(DatabaseClient client){
RelationalMappingContext context = new RelationalMappingContext();
context.afterPropertiesSet();
return new R2dbcRepositoryFactory(client, context);
}
#Bean
AlbumReactRepository albumReactRepository(R2dbcRepositoryFactory factory){
return factory.getRepository(AlbumReactRepository.class); <-- exceptions occurs
}
...
}
Some related dependency information as the followings:
+--- org.springframework.data:spring-data-jdbc:1.0.0.r2dbc-SNAPSHOT
| +--- org.springframework.data:spring-data-commons:2.1.1.BUILD-SNAPSHOT -> 2.0.10.RELEASE (*)
...
+--- org.springframework.security:spring-security-data -> 5.0.8.RELEASE
| +--- javax.xml.bind:jaxb-api:2.3.0
| +--- org.springframework.data:spring-data-commons:2.0.10.RELEASE (*)
...
| +--- org.springframework.data:spring-data-jpa:2.0.10.RELEASE
| | +--- org.springframework.data:spring-data-commons:2.0.10.RELEASE
How to fix this problem?
Make sure AlbumReactRepository is extending
org.springframework.data.repository.reactive.ReactiveCrudRepository
and not
org.springframework.data.repository.CrudRepository
I don't know how to configure GuiceApplicationBuilder in such a way, that I am able to load controllers that require a DatabaseConfigProvider to be injected.
I'd like to specify an alternative postgres database for testing, or an in memory database (if that is possible).
Code
class User
extends MySpecs
with OneAppPerTest
{
override def newAppForTest( testData: TestData ) = new GuiceApplicationBuilder()
// Somehow bind a database here, I guess?
.build()
"A test" should "test" in
{
val result = Application.instanceCache[api.controller.User]
.apply( app )
.list()( FakeRequest() )
...
}
}
Stacktrace
[info] - should return an entity *** FAILED ***
[info] com.google.inject.ConfigurationException: Guice configuration errors:
[info]
[info] 1) No implementation for play.api.db.slick.DatabaseConfigProvider was bound.
[info] while locating play.api.db.slick.DatabaseConfigProvider
[info] for parameter 1 at api.controller.User.<init>(User.scala:22)
[info] while locating api.controller.User
[info]
[info] 1 error
[info] at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1042)
[info] at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1001)
[info] at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
[info] at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:321)
[info] at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:316)
[info] at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:234)
[info] at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:234)
[info] at play.utils.InlineCache.fresh(InlineCache.scala:69)
[info] at play.utils.InlineCache.apply(InlineCache.scala:55)
[info] ...
You need to add a configuration to your GuiceApplicationBuilder(), then everything should be handled automatically by play framework. Something like this should help:
val app = new GuiceApplicationBuilder()
.configure(
Configuration.from(
Map(
"slick.dbs.YOURDBNAME.driver" -> "slick.driver.H2Driver$",
"slick.dbs.YOURDBNAME.db.driver" -> "org.h2.Driver",
"slick.dbs.YOURDBNAME.db.url" -> "jdbc:h2:mem:",
"slick.dbs.default.driver" -> "slick.driver.MySQLDriver$",
"slick.dbs.default.db.driver" -> "com.mysql.jdbc.Driver"
)
)
)
.in(Mode.Test)
.build()
There is a little bit of setting up in this approach but the final result is fair. First of all start with implementing your own GuiceApplicationLoader by extending it. See my answer how to implement it. Why your own application loader? You can specify different configs/modules per Prod/Dev/Test modes - as well as different data sources. Your main application.conf wouldn't have data source configured. Instead, you would move it to environment specific configurations which would be merged with main configuration by application loader anyway. Your dev.conf would look as follows:
slick.dbs {
default {
driver = "slick.driver.PostgresDriver$",
db {
driver = "org.postgresql.Driver",
url = "jdbc:postgresql://localhost:5432/dev",
user = "postgres"
password = "postgres"
}
}
}
And the trick now is to use same data source name, in this case default, for all other configurations (the database url, drivers, credentials etc. would be different). With such setup, your evolutions will be applied to your test and dev database. Your test.conf could look as follows:
slick.dbs {
default {
// in memory configuration
}
}
In your tests, use WithApplicationLoader with your custom application loader instead and thats it.
#RunWith(classOf[JUnitRunner])
class ApplicationSpec extends Specification {
"Application" should {
"return text/html ok for home" in new WithApplicationLoader(new CustomApplicationLoader) {
val home = route(FakeRequest(routes.ApplicationController.home())).get
status(home) must equalTo(OK)
contentType(home) must beSome.which(_ == "text/html")
}
}
}
Within the test itself, you have an access to app: Application value:
val service = app.injector.instanceOf(classOf[IService])
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.