JHipster Post REST API Displays SQL Error - spring

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);

Related

Spring SimpleJdbcInsert fails with 'INSERT has more target columns than expressions'

I am using a SimpleJdbcInsert to insert rows into a PostgreSQL database. However, I get an the following error:
Caused by: org.postgresql.util.PSQLException: ERROR: INSERT has more
target columns than expressions.
org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL [INSERT
INTO product (product_id,product_name,product_code,in_
stock,product_category) VALUES(?)]; SQL state [25P02]; error code [0];
ERROR: current transaction is aborted, commands ignored until end of
transaction block; nested exception is
org.postgresql.util.PSQLException: ERROR: current transaction is
aborted, commands ignored until end of transaction block
The number columns is exactly the same as the number of values I am trying to insert when I print out the MapSqlParameterSource object shown below:
Parameters Names ::
[
product_id,
product_name,
product_code,
in_ stock,
product_category
]
Parameters Values :: [{
product_id=1518,
product_name=Sofa,
product_code=150,
in_stock=true,
product_category=null,
}]
The product_id is the primary key and it is not null. Could the problem be because I am not using an auto-generated primary key? I still do not understand why that would be a problem.
The columns shown in the error message are precisely the same as the columns in the parameter list I'm printing. The values also tally with the number of columns as well, so I'm really baffled why PostgreSQL is giving this error. Please help!
I was able to solve it with a different solution to using Spring JDBC.

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?

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

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\"")

PostgreSQL 9.4 create table if not exists

I created tables on heroku using the following DDL.
CREATE TABLE IF NOT EXISTS "Team"(
"id" SERIAL,
"name" varchar(50) NOT NULL,
"description" varchar(255)
);
CREATE TABLE IF NOT EXISTS "Member"(
"id" SERIAL,
"name" varchar(50) NOT NULL,
"emp_number" integer NOT NULL,
"position" varchar(100) NOT NULL,
"team_id" integer references "Team"("id")
);
I got the following error:
play.api.UnexpectedException: Unexpected exception[ProvisionException: Unable to provision, see the following errors:
1) Error injecting constructor, javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [CREATE TABLE IF NOT EXISTS "Team"(]
at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:35)
at play.db.jpa.DefaultJPAApi$JPAApiProvider.class(DefaultJPAApi.java:30)
...
1 error]
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:191) ~[com.typesafe.play.play_2.11-2.4.2.jar:2.4.2]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:261) ~[com.typesafe.play.play_2.11-2.4.2.jar:2.4.2]
at play.api.GlobalSettings$class.onError(GlobalSettings.scala:179) [com.typesafe.play.play_2.11-2.4.2.jar:2.4.2]
...
Caused by: com.google.inject.ProvisionException: Unable to provision, see the following errors:
1) Error injecting constructor, javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [CREATE TABLE IF NOT EXISTS "Team"(]
at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:35)
...
1 error
at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025) ~[com.google.inject.guice-4.0.jar:na]
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051) ~[com.google.inject.guice-4.0.jar:na]
...
Caused by: javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [CREATE TABLE IF NOT EXISTS "Team"(]
at org.hibernate.jpa.internal.schemagen.GenerationTargetToDatabase.acceptCreateCommands(GenerationTargetToDatabase.java:64) ~[org.hibernate.hibernate-entitymanager-4.3.9.Final.jar:4.3.9.Final]
...
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at end of input
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ~[org.hibernate.hibernate-entitymanager-4.3.9.Final.jar:4.3.9.Final]
...
Position: 35
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270) ~[org.postgresql.postgresql-9.4-1201-jdbc41.jar:9.4]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998) ~[org.postgresql.postgresql-9.4-1201-jdbc41.jar:9.4]
...
The error is quite obvious. The SQL contains errors. I am quite new to postgres sql. At least I know the current version used by heroku supports if not exists syntax but I am not sure where I went wrong.
Is anybody good at PostgreSQL here?
If you had run this query directly, you would have gotten the error:
ERROR: there is no unique constraint matching given keys for referenced table "Team"
This gives you a clue that there's something missing to identify the columns in the "Team" table uniquely. You have declared that the ids of the tables are serials, but forgot to add primary key constraints. Adding this, will let you execute the query:
CREATE TABLE IF NOT EXISTS "Team"(
"id" SERIAL primary key,
...
);
CREATE TABLE IF NOT EXISTS "Member"(
"id" SERIAL primary key,
...
);

SQL Minus and lower/upper dont work together in Jdbc

i got a HSQLDB 2.2.9 and the following statement:
(SELECT lower(MyCol) FROM MyTable WHERE ID = ?)
MINUS
(SELECT lower(MyCol) FROM MyTable WHERE ID = ?)
And it works in my Squirrel. But when i execute this in my program which uses Jdbc i get the following exception:
Exception in thread "main" org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [(SELECT lower(MyCol) FROM MyTable WHERE ID = ? ) MINUS (SELECT lower(MyCol) FROM MyTable WHERE ID_CENTER = ?)]; Column not found: MyCol; nested exception is java.sql.SQLException: Column not found: MyCol
If i delete the lower() that statement works but its case sensitive which i want to eliminate here.
Can please someone tell me why i get this error and how to fix it?
This exception is not thrown by HSQLDB 2.2.9. If the column could not be found, the exception message would be in this form:
user lacks privilege or object not found: MYCOL
Please check your Spring data source settings.

Resources