Dropwizard example package compile-error - java

I'm totally new to Java and its tools, I would like to use Dropwizard framework.
I found an example found in its repository, however I could not run it.
As its said in the README.md, I need to run mvn package. However, as I understood, Maven tries to run integration tests but exception is thrown. The stack trace is like so:
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.975 sec << FAILURE! - in com.example.helloworld.IntegrationTest
com.example.helloworld.IntegrationTest Time elapsed: 5.974 sec <<< ERROR!
liquibase.exception.LockException: liquibase.exception.DatabaseException: Unknown data type: "İNT"; SQL statement:
CREATE TABLE PUBLIC.DATABASECHANGELOGLOCK (ID İNT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED TIMESTAMP, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID)) [50004-192] [Failed SQL: CREATE TABLE PUBLIC.DATABASECHANGELOGLOCK (ID İNT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED TIMESTAMP, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID))]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.command.Parser.parseColumnWithType(Parser.java:4079)
at org.h2.command.Parser.parseColumnForTable(Parser.java:3937)
at org.h2.command.Parser.parseCreateTable(Parser.java:5972)
at org.h2.command.Parser.parseCreate(Parser.java:4237)
at org.h2.command.Parser.parsePrepared(Parser.java:362)
at org.h2.command.Parser.parse(Parser.java:317)
at org.h2.command.Parser.parse(Parser.java:289)
at org.h2.command.Parser.prepareCommand(Parser.java:254)
at org.h2.engine.Session.prepareLocal(Session.java:560)
at org.h2.engine.Session.prepareCommand(Session.java:501)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1202)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
at liquibase.executor.jvm.JdbcExecutor$ExecuteStatementCallback.doInStatement(JdbcExecutor.java:299)
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:55)
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:107)
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:97)
at liquibase.lockservice.StandardLockService.init(StandardLockService.java:94)
at liquibase.lockservice.StandardLockService.acquireLock(StandardLockService.java:206)
at liquibase.lockservice.StandardLockService.waitForLock(StandardLockService.java:170)
at liquibase.Liquibase.update(Liquibase.java:196)
at liquibase.Liquibase.update(Liquibase.java:192)
at liquibase.Liquibase.update(Liquibase.java:188)
at liquibase.Liquibase.update(Liquibase.java:181)
at io.dropwizard.migrations.DbMigrateCommand.run(DbMigrateCommand.java:68)
at io.dropwizard.migrations.DbCommand.run(DbCommand.java:52)
at io.dropwizard.migrations.AbstractLiquibaseCommand.run(AbstractLiquibaseCommand.java:64)
at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:85)
at io.dropwizard.cli.Cli.run(Cli.java:75)
at io.dropwizard.Application.run(Application.java:79)
at com.example.helloworld.IntegrationTest.migrateDb(IntegrationTest.java:38)
I think it has some issues with locale, because my operating system is OS X 10.11 Turkish, where we capitalize strings 'i' to 'İ', not 'I'.
I'm using IntelliJ IDEA, could you tell me how can I change current locale for the guy who is tested (I don't know it's JVM or Maven or something...)?
As it's requested, my migrations.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet id="1" author="codahale">
<createTable tableName="people">
<column name="id" type="bigint" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="fullName" type="varchar(255)">
<constraints nullable="false"/>
</column>
<column name="jobTitle" type="varchar(255)"/>
</createTable>
</changeSet>
</databaseChangeLog>

It should have been caused by your locale settings of Java Virtual Machine (JVM).
Simply change your locale to English by opening your terminal or console (for Windows) and running the following command.
set JAVA_ARGS=-Duser.language=en -Duser.region=US %JAVA_ARGS%
To automate that, you might need to export the environment variable in your terminal startup script, something like .bash_profile.

Related

Hibernate trying to create tables in upgraded Mysql-8 even if table exists

We are upgrading Mysql-5.7 to Mysql-8.0.28 with Mysql-8.0.28 Connector.
Here the issue is, Hibernate trying to recreate all tables even if all tables are exists using hbm2ddl.auto as update.
Software Version Details :
Hibernate-5.3.17,
Mysql Database-8.0.28,
Mysql Connector-8.0.28.
hibernate.cfg.xml
<session-factory>
<property name="show_sql">false</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
</property>
<property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>
<property name="cacheManagerName">ehcache-agora</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="c3p0.timeout">3000</property>
<property name="c3p0.idle_test_period">300</property>
Logs information :
[11 Jul 2022 15:42:32 IST][INFO] HHH000130: Instantiating explicit connection provider: org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl
[11 Jul 2022 15:42:32 IST][WARN] GenerationTarget encountered exception accepting command : Error executing DDL "create table ALERT (ID bigint not null, NAME varchar(255), DATA longtext, TYPE varchar(255), USER_ID bigint, CREATED_DATE datetime(6), primary key (ID)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table ALERT (ID bigint not null, NAME varchar(255), DATA longtext, TYPE varchar(255), USER_ID bigint, CREATED_DATE datetime(6), primary key (ID)) engine=InnoDB" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at com.sathya.sdp.server.ThreadSession.<clinit>(ThreadSession.java:88)
at com.sathya.sdp.server.presentation.PlatformBuilder.initialize(PlatformBuilder.java:66)
at com.sathya.sdp.server.presentation.PlatformServlet.initialize(PlatformServlet.java:320)
at com.sathya.sdp.server.presentation.PlatformServlet.init(PlatformServlet.java:49)
at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
Caused by: java.sql.SQLSyntaxErrorException: Table 'ALERT' already exists
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
at com.mysql.cj.jdbc.StatementWrapper.execute(StatementWrapper.java:529)
at org.jboss.jca.adapters.jdbc.WrappedStatement.execute(WrappedStatement.java:198)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 40 more
Thanks in Advance,
P.Sathya

Liquibase doesn't load *.sql from classpath inside of changeSet

I need configure changeSet executing sql loaded from jar.
I have internal project changeSet that works correctly
<changeSet id="1" author="sergii" dbms="h2">
<sqlFile
encoding="utf8"
path="schema-ms-sql.0.0.1.sql"
relativeToChangelogFile="true"
splitStatements="true"
stripComments="true"/>
</changeSet>
Some scripts are provided from different libraries (in my case it is spring-boot-starter-batch), for example:
classpath:/org/springframework/batch/core/schema-h2.sql
Note that jar is in the project and accessible (build \ test\ run times).
As result I need register one also into my changeSet, trying:
<changeSet id="2" author="sergii" dbms="h2">
<sqlFile
encoding="utf8"
path="classpath*:/org/springframework/batch/core/schema-h2.sql"
relativeToChangelogFile="true"
splitStatements="true"
stripComments="true"/>
</changeSet>
and it doesn't work with any configuration (like "classpath:/org/springframework/batch/core/schema-h2.sql", "/org/springframework/batch/core/schema-h2.sql", "org/springframework/batch/core/schema-h2.sql", "classpath*:/org/springframework/batch/core/schema-h2.sql" and so on) because of
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.UnexpectedLiquibaseException: java.io.IOException: File does not exist: 'classpath*:/org/springframework/batch/core/schema-h2.sql'
I know using spring I could use auto configuration, but I'm interested in liquibase auditing...
Is any ideas how to make packaged scripts working via changeSet or include into liquibase auditing?
Solution is to change attribute for sqlFile tag:
relativeToChangelogFile="false"
Result changeSet below:
<changeSet id="2" author="sergii" dbms="h2">
<sqlFile
encoding="utf8"
path="classpath:/org/springframework/batch/core/schema-h2.sql"
relativeToChangelogFile="false"
splitStatements="true"
stripComments="true"/>
</changeSet>
Example for separate changelog.yaml file with relative path:
databaseChangeLog:
- changeSet:
id: my_script_1
changes:
- sqlFile:
dbms: mysql
encoding: utf8
path: db/changelog/0_0_1/my_script_1.sql
relativeToChangelogFile: false
splitStatements: true
stripComments: true
rollback:
- sqlFile:
dbms: mysql
encoding: utf8
path: db/changelog/0_0_1/my_script_1_rollback.sql
relativeToChangelogFile: false
splitStatements: true
stripComments: true
- changeSet:
id: my_script_2
changes:
- sqlFile:
dbms: mysql
encoding: utf8
path: db/changelog/0_0_1/my_script_2.sql
relativeToChangelogFile: false
splitStatements: true
stripComments: true
rollback:
- sqlFile:
dbms: mysql
encoding: utf8
path: db/changelog/0_0_1/my_script_2_rollback.sql
relativeToChangelogFile: false
splitStatements: true
stripComments: true

EclipseLink: createNativeQuery exeption - org.postgresql.util.PSQLException

I'm running into a weird issue that hasn't been reported by others from what I could tell, there may be a bug when using createNativeQuery. I have tried so many things to understand why to no avail.
Current Environment:
EclipseLink 2.7.3 JPA provider
PostgreSQL 10.6.1 Database
Eclipse Photon IDE
JRE 1.8.0_121
When executing:
Long total = (Long) em.createNativeQuery("Project.count").getSingleResult();
It's throwing the following:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax error at or near "Project"
Position: 1
Error Code: 0
Call: Project.count
Query: DataReadQuery(sql="Project.count")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:391)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:264)
at org.eclipse.persistence.internal.jpa.QueryImpl.getSingleResult(QueryImpl.java:530)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:404)
at com.bbandt.util.testers.ProjectTester.ProjectVersionMapping(ProjectTester.java:43)
at com.bbandt.util.testers.ProjectTester.main(ProjectTester.java:21)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax error at or near "Project"
Position: 1
Error Code: 0
Call: Project.count
Query: DataReadQuery(sql="Project.count")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:342)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:691)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:567)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2096)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:603)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:275)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:261)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:332)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelect(DatasourceCallQueryMechanism.java:314)
at org.eclipse.persistence.queries.DataReadQuery.executeNonCursor(DataReadQuery.java:199)
at org.eclipse.persistence.queries.DataReadQuery.executeDatabaseQuery(DataReadQuery.java:154)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:914)
at org.eclipse.persistence.queries.DataReadQuery.execute(DataReadQuery.java:139)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:813)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2981)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1895)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1877)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1842)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:262)
... 4 more
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "Project"
Position: 1
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:106)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:1015)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:651)
... 21 more
Persistence.xml (truncated purposely )
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="LocalPostgreSQL" transaction-type="RESOURCE_LOCAL">
<mapping-file>META-INF/orm.xml</mapping-file>
<mapping-file>META-INF/Queries.xml</mapping-file>
<!-- <mapping-file>META-INF/ResultsetMappings.xml</mapping-file>
-->
<class>com.bbandt.jpa.converters.UUIDAttributeConverter</class>
<class>model.Component</class>
<class>model.ComponentVulnerability</class>
<class>model.ComponentVulnerabilityPK</class>
<class>model.Project</class>
<class>model.ProjectVersion</class>
<class>model.ProjectVersionPK</class>
ORM.xml contents:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">
<named-native-query name="Project.count">
<query>Select count(*) as total from public.project</query>
</named-native-query>
</entity-mappings>
From what I could tell, the named native query is not getting resolved back to the actual SQL contents.
Executing this works (and it resolves the named-native-query name "Project.count"):
Long total = (Long) em.createNamedQuery("Project.count").getSingleResult();
This also works:
Long total = (Long) em.createNativeQuery("Select count(*) from project").getSingleResult();
I didn't want to resort to JPQL for other reasons unimportant to this thread and I also need to implement SQL Resultset Mappings.
Any insight on this would be greatly appreciated. I truly ran out of ideas.
createNamedQuery: Used to define queries wthe ith name in mapping file or annotation
createNativeQuery: Used to execute native/pure SQL queries
Since you use createNativeQuery method with a named query you are getting above error

mybatis insert throwing org.apache.ibatis.type.TypeException

I have a insert statement in my xml as below.
<insert id="insertQuote" parameterMap="quoteParam">
<selectKey keyProperty="id" resultType="string">
select seq_quote_id.nextval as id from dual
</selectKey>
insert into insq_quotation (quote_id, search_product_type,
coverage_start_date, quote_date, zip, create_date, business_id,
county, status
)
values(? ,?, ?, sysdate, ?, default, 200, ?, 999)
</insert>
Here is the parameter map
<parameterMap id="quoteParam" type="com.product.vo.QuoteVO">
<parameter property="id" jdbcType="INTEGER"/>
<parameter property="regionType" jdbcType="INTEGER" typeHandler="com.product.mybatis.RegionTypeHandler"/>
<parameter property="productType" jdbcType="INTEGER" typeHandler="com.product.mybatis.ProductTypeHandler"/>
<parameter property="coverageStartDate" jdbcType="DATE"/>
<parameter property="zip" jdbcType="VARCHAR"/>
<parameter property="county" jdbcType="VARCHAR"/>
</parameterMap>
The QuoteVO has all the attributes populated. This works fine in ibatis. But i'm migrating to mybatis and when I run the application, I'm getting the below error. Application uses Oracle DB and Spring. Datatype for county in DB is VARCHAR2. Please advice.
2017-05-09 10:04:19 INFO IFPProductServiceImpl:36 - calling saveQuote QuoteVO [quoteId=null, applicationType=I, coverageStartDate=Tue May 09 10:04:18 PDT 2017, zip=90001, county=LA, subscriberNumber=12345]
2017-05-09 10:04:20 ERROR ExceptionControllerAdvice:17 - org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='county', mode=null, javaType=class java.lang.String, jdbcType=VARCHAR, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #6 with JdbcType VARCHAR . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: Invalid column index

Cannot create tables and load data in H2 using JPA

I have a JPA project that uses Hibernate and H2. The following is the maven pom dependency list:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.181</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
The following is the project structure:
The following is the content of blood_donor_create.sql:
CREATE TABLE IF NOT EXISTS `blood_type` (
`id` integer NOT NULL,
`blood_type` char(3) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `donation` (
`id` bigint NOT NULL auto_increment,
`date` date NOT NULL,
`location` varchar(150) NOT NULL,
`donor_id` bigint NOT NULL,
PRIMARY KEY (`id`),
KEY `donation_donor` (`donor_id`),
CONSTRAINT `donation_donor` FOREIGN KEY (`donor_id`) REFERENCES `donor` (`id`)
)
CREATE TABLE IF NOT EXISTS `donor` (
`id` bigint NOT NULL auto_increment,
`name` varchar(50) NOT NULL,
`myanmar_name` varchar(100) NOT NULL,
`email` varchar(50) NOT NULL,
`facebook` varchar(50) NOT NULL,
`phone` integer NOT NULL,
`blood_type_id` integer NOT NULL,
PRIMARY KEY (`id`),
KEY `donor_blood_type` (`blood_type_id`),
CONSTRAINT `donor_blood_type` FOREIGN KEY (`blood_type_id`) REFERENCES `blood_type` (`id`)
)
And the following is the content of blood_donor_load.sql:
INSERT INTO `blood_type` (`id`, `blood_type`) VALUES
(1, 'A+'),
(2, 'A-'),
(3, 'B+'),
(4, 'B-'),
(5, 'O+'),
(6, 'O-'),
(7, 'AB+'),
(8, 'AB-');
The following is the content of persistence.xml:
<persistence-unit name="BloodDonorPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:file:~/blooddonor"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="javax.persistence.schema-generation.create-source" value="script"/>
<property name="javax.persistence.schema-generation.create-script-source" value="sql/blood_donor_load.sql"/>
<property name="javax.persistence.sql-load-script-source" value="sql/blood_donor_load.sql"/>
</properties>
</persistence-unit>
Running the program causes the following exceptions:
Exception in thread "main" javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [INSERT INTO `blood_type` (`id`, `blood_type`) VALUES]
at org.hibernate.jpa.internal.schemagen.GenerationTargetToDatabase.acceptCreateCommands(GenerationTargetToDatabase.java:64)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.doGeneration(JpaSchemaGenerator.java:507)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.access$300(JpaSchemaGenerator.java:69)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$Generation.execute(JpaSchemaGenerator.java:184)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.performGeneration(JpaSchemaGenerator.java:76)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at org.bitbucket.infovillavendor.blooddonor.Launcher.main(Launcher.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.h2.jdbc.JdbcSQLException: Table "BLOOD_TYPE" not found; SQL statement:
INSERT INTO `blood_type` (`id`, `blood_type`) VALUES [42102-181]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.command.Parser.readTableOrView(Parser.java:5227)
at org.h2.command.Parser.readTableOrView(Parser.java:5204)
at org.h2.command.Parser.parseInsert(Parser.java:1025)
at org.h2.command.Parser.parsePrepared(Parser.java:401)
at org.h2.command.Parser.parse(Parser.java:305)
at org.h2.command.Parser.parse(Parser.java:277)
at org.h2.command.Parser.prepareCommand(Parser.java:242)
at org.h2.engine.Session.prepareLocal(Session.java:446)
at org.h2.engine.Session.prepareCommand(Session.java:388)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1189)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:171)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:159)
at org.hibernate.jpa.internal.schemagen.GenerationTargetToDatabase.acceptCreateCommands(GenerationTargetToDatabase.java:61)
... 18 more
What might be wrong here?
I don't think you need the quotes in the table name in the creation or insertion.
The best thing to do is to install the H2 database, which has a front-end, onto your computer and paste the create and load statements into the console so it can highlight the errors and give you meaningful messages.

Categories