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

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.

Related

Failed Executing DbCommand during Entity Framework migration in .NetCORE Web API --

I created a .netcore webapi targeting framework 3.1. Added the required classes and code in ApplicationUser and ApplicationDbContext and in startup services.AddDbContext<..........
Then I ran command add-migration IniCr which built and ran ok.
But when I ran the update-database console window shows the following error:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (21ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [AspNetUsers] (
[Id] nvarchar(450) NOT NULL,
[UserName] nvarchar(256) NULL,
[NormalizedUserName] nvarchar(256) NULL,
[Email] nvarchar(256) NULL,
[NormalizedEmail] nvarchar(256) NULL,
[EmailConfirmed] bit NOT NULL,
[PasswordHash] nvarchar(max) NULL,
[SecurityStamp] nvarchar(max) NULL,
[ConcurrencyStamp] nvarchar(max) NULL,
[PhoneNumber] nvarchar(max) NULL,
[PhoneNumberConfirmed] bit NOT NULL,
[TwoFactorEnabled] bit NOT NULL,
[LockoutEnd] datetimeoffset NULL,
[LockoutEnabled] bit NOT NULL,
[AccessFailedCount] int NOT NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY ([Id])
);
Failed executing DbCommand (21ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [AspNetUsers] (
[Id] nvarchar(450) NOT NULL,
[UserName] nvarchar(256) NULL,
[NormalizedUserName] nvarchar(256) NULL,
[Email] nvarchar(256) NULL,
[NormalizedEmail] nvarchar(256) NULL,
[EmailConfirmed] bit NOT NULL,
[PasswordHash] nvarchar(max) NULL,
[SecurityStamp] nvarchar(max) NULL,
[ConcurrencyStamp] nvarchar(max) NULL,
[PhoneNumber] nvarchar(max) NULL,
[PhoneNumberConfirmed] bit NOT NULL,
[TwoFactorEnabled] bit NOT NULL,
[LockoutEnd] datetimeoffset NULL,
[LockoutEnabled] bit NOT NULL,
[AccessFailedCount] int NOT NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY ([Id])
);
System.AggregateException: An error occurred while writing to logger(s). (Cannot open log for source '.NET Runtime'. You may not have write access.)
---> System.InvalidOperationException: Cannot open log for source '.NET Runtime'. You may not have write access.
---> System.ComponentModel.Win32Exception (1722): The RPC server is unavailable.
--- End of inner exception stack trace ---
at System.Diagnostics.EventLogInternal.OpenForWrite(String currentMachineName)
at System.Diagnostics.EventLogInternal.InternalWriteEvent(UInt32 eventID, UInt16 category, EventLogEntryType type, String[] strings, Byte[] rawData, String currentMachineName)
at System.Diagnostics.EventLogInternal.WriteEvent(EventInstance instance, Byte[] data, Object[] values)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Object[] values)
at Microsoft.Extensions.Logging.EventLog.WindowsEventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category)
at Microsoft.Extensions.Logging.EventLog.EventLogLogger.WriteMessage(String message, EventLogEntryType eventLogEntryType, Int32 eventId)
at Microsoft.Extensions.Logging.EventLog.EventLogLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
at Microsoft.Extensions.Logging.Logger.<Log>g__LoggerLog|12_0[TState](LogLevel logLevel, EventId eventId, ILogger logger, Exception exception, Func`3 formatter, List`1& exceptions, TState& state)
--- End of inner exception stack trace ---
at Microsoft.Extensions.Logging.Logger.ThrowLoggingError(List`1 exceptions)
at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
at Microsoft.Extensions.Logging.LoggerMessage.<>c__DisplayClass10_0`6.<Define>b__0(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception)
at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition`6.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, WarningBehavior warningBehavior, TParam1 arg1, TParam2 arg2, TParam3 arg3, TParam4 arg4, TParam5 arg5, TParam6 arg6)
at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.LogCommandError(IDiagnosticsLogger`1 diagnostics, DbCommand command, TimeSpan duration, EventDefinition`6 definition)
at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.CommandError(IDiagnosticsLogger`1 diagnostics, IRelationalConnection connection, DbCommand command, DbContext context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, Exception exception, DateTimeOffset startTime, TimeSpan duration)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
An error occurred while writing to logger(s). (Cannot open log for source '.NET Runtime'. You may not have write access.)
When I check my mssql server I see a new db created as per the name I gave in appsettinngs.json but only with 1 table - efmigrationhistory.
Why such? What mistake did I make? What needs to be done to get the migration going and create the full database with aspnet identity? Please suggest the correction;
Some help needed.
I have resolved the issue.
I ran the query
select ##version
and found that I was running version 2005 of the database engine which does not have the data type datetimeoffset.
I went through the installation process of Sql Server 2019.
And then ran the code migrations of my project allover again. It completed just fine! No issues whatsoever anymore in doing code-migrations,
Does running visual studio as administrator solve or changes the error?
You have a logger configured which writes to Windows Event log. The account you are running your migrations under does not have access to writing logs, which is why the whole operation is failing.
Either grant it the necessary permissions or don't write to event log.
P.S.: Since your application is likely cross-platform otherwise, I question the wisdom of writing to Windows specific logs.

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.

42P07: Error while updating Postgre Entity Framework Core database

I am trying to update the database using the EntityFramework migration, but this error crashes. I started looking at what they write on this issue, but everywhere the same thing, that do not use EnsureCreated in a startup and that's it. I don't have anything like that in a startup, here's the code in a startup:
services.AddDbContext<ApplicationDbContext>();
services.AddIdentity<IdentityUserModel, IdentityRole>(
options => options.SignIn.RequireConfirmedAccount = false
)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Well, of course, adding authorization, adding providers, and so on. But as soon as I try to start the migration, the error falls below.
Who faced this problem or knows how to solve it, please tell me.
Thank you very much for your answers!
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "AspNetRoles" (
"Id" text NOT NULL,
"Name" character varying(256) NULL,
"NormalizedName" character varying(256) NULL,
"ConcurrencyStamp" text NULL,
CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);
Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "AspNetRoles" (
"Id" text NOT NULL,
"Name" character varying(256) NULL,
"NormalizedName" character varying(256) NULL,
"ConcurrencyStamp" text NULL,
CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);
Npgsql.PostgresException (0x80004005): 42P07: отношение "AspNetRoles" уже существует
at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult()
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Exception data:
Severity: ОШИБКА
SqlState: 42P07
MessageText: отношение "AspNetRoles" уже существует
File: d:\pginstaller.auto\postgres.windows-x64\src\backend\catalog\heap.c
Line: 1094
Routine: heap_create_with_catalog
42P07: отношение "AspNetRoles" уже существует
This error seems to be a "duplicated relation" in Postgres. This means that you are probably trying to recreate a database table that already exists. You should double check your migrations - it's possible that for some reason it's trying to recreate a database that already exists.
Another reason would be some sort of unsync'ing between your migration and the database - maybe someone else created the table manually, for instance?

Caused by: org.postgresql.util.PSQLException: Bad value for type long : \x

I am using Quartz API 2.3.0 with Spring boot Parent 2.0.5 and postgresql version 9.2-1002-jdbc4.
I get below error when the application retrieves data from qrtz_job_triggers table.
org.springframework.context.ApplicationContextException: Failed to start bean 'schedulerFactoryBean'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Couldn't retrieve trigger: Bad value for type long : \x [See nested exception: org.postgresql.util.PSQLException: Bad value for type long : \x]]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:185)
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:53)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:360)
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:158)
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:122)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:885)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:161)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265)
at com.ericsson.cis.healer.Application.main(Application.java:17)
Caused by: org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Couldn't retrieve trigger: Bad value for type long : \x [See nested exception: org.postgresql.util.PSQLException: Bad value for type long : \x]]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:782)
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182)
... 14 common frames omitted
Caused by: org.quartz.SchedulerConfigException: Failure occured during job recovery.
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:697)
at org.quartz.core.QuartzScheduler.start(QuartzScheduler.java:539)
at org.quartz.impl.StdScheduler.start(StdScheduler.java:142)
at org.springframework.scheduling.quartz.SchedulerFactoryBean.startScheduler(SchedulerFactoryBean.java:707)
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:779)
... 15 common frames omitted
Caused by: org.quartz.JobPersistenceException: Couldn't retrieve trigger: Bad value for type long : \x
at org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger(JobStoreSupport.java:1538)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverMisfiredJobs(JobStoreSupport.java:984)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverJobs(JobStoreSupport.java:871)
at org.quartz.impl.jdbcjobstore.JobStoreSupport$1.executeVoid(JobStoreSupport.java:843)
at org.quartz.impl.jdbcjobstore.JobStoreSupport$VoidTransactionCallback.execute(JobStoreSupport.java:3765)
at org.quartz.impl.jdbcjobstore.JobStoreSupport$VoidTransactionCallback.execute(JobStoreSupport.java:3763)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3849)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverJobs(JobStoreSupport.java:839)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:695)
... 19 common frames omitted
Caused by: org.postgresql.util.PSQLException: Bad value for type long : \x
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.toLong(AbstractJdbc2ResultSet.java:2971)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getLong(AbstractJdbc2ResultSet.java:2163)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getBlob(AbstractJdbc2ResultSet.java:378)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getBlob(AbstractJdbc2ResultSet.java:366)
at com.zaxxer.hikari.pool.HikariProxyResultSet.getBlob(HikariProxyResultSet.java)
at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.getObjectFromBlob(StdJDBCDelegate.java:3190)
at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.selectTrigger(StdJDBCDelegate.java:1780)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger(JobStoreSupport.java:1536)
... 27 common frames omitted
Below is the script for the table
CREATE TABLE qrtz_job_details
(
sched_name character varying(120) NOT NULL,
job_name character varying(200) NOT NULL,
job_group character varying(200) NOT NULL,
description character varying(250),
job_class_name character varying(250) NOT NULL,
is_durable boolean NOT NULL,
is_nonconcurrent boolean NOT NULL,
is_update_data boolean NOT NULL,
requests_recovery boolean NOT NULL,
job_data bytea,
CONSTRAINT qrtz_job_details_pkey PRIMARY KEY (job_group, job_name, sched_name)
)
WITH (
OIDS=FALSE
);
ALTER TABLE qrtz_job_details
OWNER TO postgres;
I have also tried With other postgres version i.e. 42.2.5
My application.properties file
spring.jpa.database=POSTGRESQL
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/cis_migration
spring.datasource.username=postgres
spring.datasource.password=root
spring.jpa.hibernate.hbm2ddl-auto=validate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
spring.quartz.job-store-type=jdbc
spring.quartz.jdbc.initialize-schema=never
spring.quartz.properties.org.quartz.scheduler.instanceName=first
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.quartz.properties.org.quartz.jobStore.isClustered=true
spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
spring.quartz.properties.org.quartz.jobStore.useProperties=true

JPA #ElementCollection [List<String>] deletion error, using play Framework 1.2.7

I want to delete a model object and that object has a list of string collection. I am using Play Framework 1.2.7.
Class structure as follows :
#Entity
#Table(name = "DATASET_CORE")
#NamedQueries(value = {
#NamedQuery(name = "datasetcore.delete", query = "DELETE FROM DataSetCore dataCore WHERE dataCore.id = :dataCoreId")
})
public class DataSetCore extends Model {
:
#Required(message = "dataset.keyword.required")
#Column(nullable = false,name = "KEYWORD")
#ElementCollection(fetch = FetchType.LAZY)
public List<String> keywords;
:
}
My Deletion code as follows:
Query q = Publish.em().createNamedQuery("datasetcore.delete");
q.setParameter("dataCoreId", dataSet.id);
q.executeUpdate();
It gives following error:
15:33:30,053 WARN ~ SQL Error: 23503, SQLState: 23503
15:33:30,053 ERROR ~ Referential integrity constraint violation: "FK9B153AF2E51FF179: PUBLIC.DATASETCORE_KEYWORDS FOREIGN KEY(DATASETCORE_ID) REFERENCES PUBLIC.DATASET_CORE(ID) (2)"; SQL sta
tement:
delete from DATASET_CORE where id=? [23503-166]
ERROR.....
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute update query
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1389)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1317)
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1399)
at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:108)
at com.hbase.metadata.services.DataSetCoreService.delete(DataSetCoreService.java:39)
at com.hbase.metadata.services.MetaDataCoreService.delete(MetaDataCoreService.java:241)
at com.hbase.ref.MetaDataCoreTestCase.deleteMetaData(MetaDataCoreTestCase.java:61)
at com.hbase.ref.MetaDataCoreTestCase.executeTest(MetaDataCoreTestCase.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at play.test.PlayJUnitRunner$StartPlay$2$1.evaluate(PlayJUnitRunner.java:114)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at play.test.PlayJUnitRunner.run(PlayJUnitRunner.java:58)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
at play.test.TestEngine.run(TestEngine.java:112)
at controllers.TestRunner$1.doJobWithResult(TestRunner.java:71)
at controllers.TestRunner$1.doJobWithResult(TestRunner.java:1)
at play.jobs.Job.call(Job.java:146)
at play.jobs.Job$1.call(Job.java:66)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute update query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.hql.ast.exec.BasicExecutor.execute(BasicExecutor.java:110)
at org.hibernate.hql.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:423)
at org.hibernate.engine.query.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:283)
at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1288)
at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:117)
at org.hibernate.ejb.QueryImpl.internalExecuteUpdate(QueryImpl.java:188)
at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:99)
... 46 more
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK9B153AF2E51FF179: PUBLIC.DATASETCORE_KEYWORDS FOREIGN KEY(DATASETCORE_ID) REFERENCES PUBLIC.DATASET_CO
RE(ID) (2)"; SQL statement:
delete from DATASET_CORE where id=? [23503-166]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:414)
at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:431)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:307)
at org.h2.table.Table.fireConstraints(Table.java:862)
at org.h2.table.Table.fireAfterRow(Table.java:879)
at org.h2.command.dml.Delete.update(Delete.java:99)
at org.h2.command.CommandContainer.update(CommandContainer.java:73)
at org.h2.command.Command.executeUpdate(Command.java:226)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:143)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:129)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.hql.ast.exec.BasicExecutor.execute(BasicExecutor.java:101)
... 52 more
I am using MySQL as a database. In database it's create a joining table. Script of that generated table is:
CREATE TABLE `datasetcore_keywords` (
`DataSetCore_id` bigint(20) NOT NULL,
`KEYWORD` varchar(255) NOT NULL,
KEY `FK9B153AF2E51FF179` (`DataSetCore_id`),
CONSTRAINT `FK9B153AF2E51FF179` FOREIGN KEY (`DataSetCore_id`) REFERENCES `dataset_core` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Can anyone help me regarding this issue.
This is copied from your error:
PUBLIC.DATASETCORE_KEYWORDS FOREIGN KEY(DATASETCORE_ID)
REFERENCES PUBLIC.DATASET_CORE(ID)
Its showing that the row you are trying to delete is referenced from another table named DATASETCORE_KEYWORDS the column DATASETCORE_ID. You have to delete that row from the table first, and only then you can do the current delete operation.