Spring Boot/JPA: Quoted reserved word column name not working - oracle

I have an Oracle table with a column named with a reserved word (TYPE)
This is defined in the entity class as
#Entity
#Table(name="PROCESS_STORAGE")
.....
#Column(name="\"TYPE\"")
private String type;
But trying to retrieve a record from the DB causes an error:
2018-01-05 11:50:54.139 WARN 9340 --- [http-nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 904, SQLState: 42000
2018-01-05 11:50:54.139 ERROR 9340 --- [http-nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00904: "PROCESSSTO0_"."type": invalid identifier
2018-01-05 11:50:54.144 ERROR 9340 --- [http-nio-8080-exec-3] 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
java.sql.SQLSyntaxErrorException: ORA-00904: "PROCESSSTO0_"."type": invalid identifier
Not quite sure what I'm missing here. It seems to be quoting the column name, but it's not finding it?
Edit
I've just realised it's a case sensitivity issue - the column is uppercase in the DB (TYPE) and in the entity definition, but for some reason it's getting converted to lowercase in the query. Still not sure why this is happening though

Think I've found a solution
here
In application.properties, need to specify
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

You need to enclose reserved keywords with backticks (`) for using it as column
TYPE is reserved in Oracle so it should be
#Column(name="`TYPE`")
private String type;

If you are using Hibernate 3.5+, try:
hibernate.globally_quoted_identifiers=true to quote all database identifiers, this is added for JPA 2.0.
In JPA 2.0, the syntax is standardized and becomes:
#Column(name="\"TYPE\"")

Related

Understanding SLQ syntax error in Flyway initial migration

I am configuring Flyway for a brand new Spring Boot project. This is the initial migration provided by DBA.
The application works in SQL Server, however I am struggling to make it work on H2 for in-memory testing purposes. The DBA didn't provide (and maybe is not going to provide) a dialect-neutral version of the DDL.
I tried to use H2's SQL Server mode
application.yaml
spring:
datasource:
url: jdbc:h2:mem:almc-be;Mode=MSSQLServer
flyway:
check-location: true
enabled: true
encoding: utf-8
locations: classpath:/flyway/${spring.datasource.platform:sqlserver}
create-schemas: true
default-schema: dbo
schemas: dbo
Beginning of the script
-- Create tables section -------------------------------------------------
-- Table dbo.Users
CREATE TABLE [dbo].[Users]
(
[UserId] Int NOT NULL,
[UserName] Nvarchar(50) NOT NULL,
[UserSurname] Nvarchar(50) NOT NULL,
[UserEmail] Nvarchar(100) NOT NULL
)
go
-- Add keys for table dbo.Users
On startup, I get the following error
2021-07-22 15:48:43.189 WARN 6316 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException:
Migration V202107221432__DDL.sql failed
---------------------------------------
SQL State : 42000
Error Code : 42000
Message : Syntax error in SQL statement "CREATE TABLE ""dbo"".""Users""
(
""UserId"" INT NOT NULL,
""UserName"" NVARCHAR(50) NOT NULL,
""UserSurname"" NVARCHAR(50) NOT NULL,
""UserEmail"" NVARCHAR(100) NOT NULL
)
GO[*]
ALTER TABLE ""dbo"".""Users"" ADD CONSTRAINT ""PK_Users"" PRIMARY KEY (""UserId"")
GO
Yes, the escape sequence is changed in the logs from the SQL file
What is the cause of the error and how can I fix it without rewriting the script into a dialect-neutral version myself?

Oracle and H2 number data type incompatibility

I am using Flyway for my Spring boot app (working with Oracle DB). I have a new script which will create a table with a number field, something like:
CREATE TABLE ENGINEER (
...
SALARY NUMBER(*, 2),
...
);
I want to debug the app with H2 database and it will run the script. H2 documentation says that NUMBER(precision, scale) is a valid data type but seems that it does not support * for precision as Oracle. So that I cannot debug it with H2, when I run the script cannot be run successfully:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-21 18:19:47.026 ERROR 25932 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException:
Migration <file-name>.sql failed
-------------------------------------------
SQL State : 42001
Error Code : 42001
Message : Syntax error in SQL statement "
CREATE TABLE ENGINEER(
...
SALARY NUMBER(*, 2),
...
)"; expected "long"; SQL statement:
CREATE TABLE ENGINEER(
...
SALARY NUMBER(*, 2),
...
) [42001-200]
Location : sql/db/migration/v04/<file-name>.sql
Line : 1
Is there any way to do so that I can keep the migration script like above but still able to debug with H2 anytime I want?
Thanks

Spring boot error ORA-01400: cannot insert NULL into ("AAKASH"."USERS"."EMAILVERIFICATIONSTATUS")

This is the error I am getting:
2020-04-14 13:44:21 WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 1400, SQLState: 23000 2020-04-14 13:44:21 ERROR o.h.e.jdbc.spi.SqlExceptionHelper - ORA-01400: cannot insert NULL into ("AAKASH"."USERS"."EMAILVERIFICATIONSTATUS")
Pretty much self-explainable. You are inserting a row into table named USERS which belongs to user AAKASH and omit value for EMAILVERIFICATIONSTATUS column which is set to NOT NULL.
What to do? Provide value for that column.
It cause by column setting(not null).
You can do
set value(not null-java or your logic)
set default value(alter column-edit table)

JHipster Post REST API Displays SQL Error

i am creating a project with using JHipster.
I have 2 entity(Course,Student) and they have many-to many relation.
So there is an another entity called Course_Student and it has 2 column(student_id,course_id).
Students(users) need to register course with clicking Register Course button on their own panel.
So i wrote a query and rest API function.
Here is my Query function:
#Modifying
#Query(value="insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (:studentId,:courseId)",nativeQuery = true)
#Transactional
void registerCourse(#Param("studentId") Long studentId, #Param("courseId") Long courseId);
And Rest API function:
#PostMapping("/registercourse/{studentId}/{courseId}")
#Timed
public ResponseEntity<Void> registerCourse(#PathVariable Long studentId,#PathVariable Long courseId) {
log.debug("REST request to register {} Course : {} Student : {}", courseId,studentId);
courseRepository.registerCourse(studentId,studentId);
return ResponseEntity.ok().headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, courseId.toString())).build();
}
But when i try to run registerCourse API with Using Swagger console displays these errors: (i entered student id:33, course id: 1)
c.m.m.w.rest.errors.ExceptionTranslator : An unexpected error occurred: could not execute statement; SQL [n/a]; constraint ["FK_COURSE_STUDENT_COURSES_ID: PUBLIC.COURSE_STUDENT FOREIGN KEY(COURSES_ID) REFERENCES PUBLIC.COURSE(ID) (33)"; SQL statement:
insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (?,?) [23506-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["FK_COURSE_STUDENT_COURSES_ID: PUBLIC.COURSE_STUDENT FOREIGN KEY(COURSES_ID) REFERENCES PUBLIC.COURSE(ID) (33)"; SQL statement:
insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (?,?) [23506-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
... 145 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK_COURSE_STUDENT_COURSES_ID: PUBLIC.COURSE_STUDENT FOREIGN KEY(COURSES_ID) REFERENCES PUBLIC.COURSE(ID) (33)"; SQL statement:
insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (?,?) [23506-196]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
... 163 common frames omitted
2017-09-08 08:58:57.099 WARN 7528 --- [ XNIO-2 task-8] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.
You are passing the student_id as the course_id, and no course exists with the id of 33. See the 3rd line of your Rest API's registerCourse:
courseRepository.registerCourse(studentId,studentId);
change to:
courseRepository.registerCourse(studentId,courseId);

ORA-00932: inconsistent datatypes: expected NUMBER got BINARY

While saving an object in database , I am getting below error:
2016-10-13 05:05:59.152 ERROR 4596 --- [nio-8090-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
2016-10-13 05:05:59.156 INFO 4596 --- [nio-8090-exec-1] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-10-13 05:05:59.184 ERROR 4596 --- [nio-8090-exec-1] o.a.c.c.C.[.[.[/].[servletContainer] : Servlet.service() for servlet [servletContainer] in context with path [] threw exception [org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement] with root cause
java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
I have Boolean fields in my entity as follows:
private Boolean isAccount;
private Boolean isEnabled;
and in Oracle db , these fields' types are Number.
When I am saving using JPA repository , using below code
Contact contact = new Contact();
contact.setIsAccount(false);
contact.setIsEnabled(false);
contactDao.save(contact);
It is throwing above error. Oracle should automatically convert Boolean to Number. Then why I am getting inconsistent datatype error? Anybody plz suggest?
Thanks.

Resources