Hsql - create schema if not exists in spring boot application - java

I am using embedded hsql db in my spring boot application and want to
create a schema only if does not exist in the db.
Assuming the schema name is XXX,
I have the below single statement schema-hsql.sql file:
CREATE SCHEMA XXX IF NOT EXISTS
However this is faing with below stack trace:
org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/xxx/schema-hsql.sql]: CREATE SCHEMA XXX IF NOT EXISTS; nested exception is java.sql.SQLSyntaxErrorException: unexpected token: IF
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:494)
at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:231)
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:48)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runScripts(DataSourceInitializer.java:157)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runSchemaScripts(DataSourceInitializer.java:81)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.init(DataSourceInitializer.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:354)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:305)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
... 65 more
Caused by: java.sql.SQLSyntaxErrorException: unexpected token: IF
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source)
at com.mchange.v2.c3p0.impl.NewProxyStatement.execute(NewProxyStatement.java:909)
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:473)
... 77 more
Caused by: org.hsqldb.HsqlException: unexpected token: IF
at org.hsqldb.error.Error.parseError(Unknown Source)
at org.hsqldb.ParserBase.unexpectedToken(Unknown Source)
at org.hsqldb.ParserDDL.getCompiledStatementBody(Unknown Source)
at org.hsqldb.ParserDDL.compileCreateSchema(Unknown Source)
at org.hsqldb.ParserDDL.compileCreate(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
at org.hsqldb.Session.executeDirectStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 81 more
What is the correct syntax for achieving this?
Thanks

use
CREATE SCHEMA IF NOT EXISTS XXX
instead of your sql
CREATE SCHEMA XXX IF NOT EXISTS
and use org.hsqldb::hsqldb v.2.4.0
See:
Hsql - create schema if not exists in spring boot application

You can also specify this in your `hibernate.cfg.xml" as following :
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
Here's full example :
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:file:db/personh2db;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
<property name="connection.username">sa</property>
<property name="connection.password"/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="com/example/model/Person.hbm.xml"/>
</session-factory>
The list of possible options for hbm2ddl.autoare,
validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session.
EDIT
You can configure hibernate properties in application.properties when you're using Spring boot.
Here's the documentation for application.properties : https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
You can find an example for hbm2ddl.auto configuration here : http://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-configure-jpa-properties

Related

shared c3p0 connection pool with hibernate and mysql on tomcat

Iam working on a project where i want to configure a shared connection pool with hibernate on tomcat.
The project is already implemented and i have to change it.
It was configured with hibernate and c3p0 connection pool where all jars where in the project itself.
I copied all jar files for connection pooling into the lib folder of tomcat.
c3p0-0.9.5.2.jar
c3p0-oracle-thin-extras-0.9.5.2.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.40-bin.jar
in server.xml i made a Resource
<Resource auth="Container"
description="DB Connection"
driverClass="com.mysql.jdbc.Driver"
maxPoolSize="40"
minPoolSize="10"
acquireIncrement="1"
name="jdbc/test"
user="admin"
password="root"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://localhost:3306/testDB" />
<ResourceLink
global="jdbc/test"
name="jdbc/test"
type="javax.sql.DataSource" />
after this i can see my connections created by the pool in phpmyadmin(mysql).
In my web.xml file of my project i created
a resource-ref.`
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/testDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
`
And my hibernate.cfg.xml file
`
</hibernate-configuration>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.datasource">java:comp/env/jdbc/testDB</property>
<mapping resource="Database.hbm.xml"/>
</hibernate-configuration>
Thats what i have done till yet. My problem is. In my project i have a sessionfactory where i set my hibernate.cfg.xml and Database.hbm.xml file.
This is now giving me a java.lang.NullPointerException.
Do i have to configure the sessionfactory also on tomcat as resource?
At Tomcat:
Jun 29, 2017 10:06:19 AM org.apache.catalina.mbeans.GlobalResourcesLifecycleListener createMBeans
SCHWERWIEGEND: Exception processing Global JNDI Resources
javax.naming.NamingException: Could not load resource factory class [Root exception is java.lang.ClassNotFoundException: myutil.hibernate.HibernateSessionFactoryTomcatFactory]
at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:82)
at javax.naming.spi.NamingManager.getObjectInstance(Unknown Source)
at org.apache.naming.NamingContext.lookup(NamingContext.java:842)
at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
at org.apache.naming.NamingContextBindingsEnumeration.nextElementInternal(NamingContextBindingsEnumeration.java:117)
at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:71)
at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:34)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:138)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:145)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:110)
at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.lifecycleEvent(GlobalResourcesLifecycleListener.java:82)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)
at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:347)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: java.lang.ClassNotFoundException: myutil.hibernate.HibernateSessionFactoryTomcatFactory
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:80)
... 23 more
Jun 29, 2017 10:06:17 AM org.apache.tomcat.util.digester.Digester endElement
WARNUNG: No rules found matching 'Server/GlobalNamingResources/ResourceLink'.
Jun 29, 2017 10:06:17 AM org.apache.catalina.core.AprLifecycleListener init
INFORMATION: The APR based Apache Tomcat Native library which allows optimal
performance in production environments was not found on the java.library.path:
EDIT
What i have not mentioned, iam using OSGI equinox and a servlet bridge.
everything that i have configured is right, the only thing i had to change in my case was to change my launch.ini
i had:
osgi.parentClassloader=app
osgi.contextClassLoaderParent=app
changing it to
osgi.parentClassloader=app
osgi.contextClassLoaderParent=fwk <--- changed
here a link where i got my help from
also using
java:/comp/env/jdbc/testDB using a slash before comp solved my problem
in your server.xml Change to this :
<Resource auth="Container"
description="DB Connection"
driverClass="com.mysql.jdbc.Driver"
maxPoolSize="40"
minPoolSize="10"
acquireIncrement="1"
name="jdbc/testDB" <!-- change -->
user="admin"
password="root"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://localhost:3306/testDB" />
and :
<ResourceLink
global="jdbc/testDB" <!--change -->
name="jdbc/testDB" <!-- & change -->
type="javax.sql.DataSource" />
And your hibernate.cfg.xml file to
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.datasource">java:comp/env/jdbc/testDB</property> <!-- ? -->
<mapping resource="Database.hbm.xml"/>
</session-factory>
</hibernate-configuration>
restart catalina.
osgi.parentClassloader=app
osgi.contextClassLoaderParent=app
changing it to
osgi.parentClassloader=app
osgi.contextClassLoaderParent=fwk <--- changed
here a link where i got my help from when i had NoInitialContextException.
javax.naming.NoInitialContextException:Cannot instantiate class: org.apache.naming.java.javaURLContextFactory (root cause classnotfound for org.apache.naming.java.javaURLContextFactory)
also using java:/comp/env/jdbc/testDB instead of java:comp/env/jdbc/testDB (slash before /comp) solved a different problem i had on the linux tomcat server(JNDI lookup exception):
NameNotFoundException.

Connection fails between MySQL and Spring MVC App

I have really tried to find a solution to this problem - but I can't seem to figure it out. I really hope you guys know what to do.
My Spring MVC application has begun to lose the connection to the database, and I don't know why. It is driving me crazy.
Spring DB setup:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://ip/database-name
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.datasource.tomcat.initialSize=5
spring.datasource.tomcat.maxActive=55
spring.datasource.tomcat.maxIdle=21
spring.datasource.tomcat.minIdle=13
spring.datasource.tomcat.testWhileIdle=true
spring.datasource.tomcat.timeBetweenEvictionRunsMillis=34000
spring.datasource.tomcat.minEvictableIdleTimeMillis=55000
spring.datasource.tomcat.validationInterval=34000
spring.datasource.tomcat.testOnBorrow=true
spring.datasource.tomcat.validationQuery=SELECT 1
spring.datasource.tomcat.removeAbandoned=true
spring.datasource.tomcat.removeAbandonedTimeout=233
spring.jpa.hibernate.ddl-auto=update
I have tried to specify 'autoReconnect=true' because I found answers, that suggested that - but it hasn't solved my problem.
Error log:
WARN 5220 --- [-nio-443-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 08S01
ERROR 5220 --- [-nio-443-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : The last packet successfully received from the server was 60,401,089 milliseconds ago. The last packet sent successfully to the server was 60,401,089 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection val
idity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
ERROR 5220 --- [-nio-443-exec-6] w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the user.
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 60,401,089 milliseconds ago. The last packet sent successfully to the server was 60,401,089 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at sun.reflect.GeneratedConstructorAccessor277.newInstance(Unknown Source) ~[na:na]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_91]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_91]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:981) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3652) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2460) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962) ~[mysql-connector-java-5.1.38.jar:5.1.38]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
... 111 common frames omitted
Caused by: java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:1.8.0_91]
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109) ~[na:1.8.0_91]
at java.net.SocketOutputStream.write(SocketOutputStream.java:153) ~[na:1.8.0_91]
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) ~[na:1.8.0_91]
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:126) ~[na:1.8.0_91]
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3633) ~[mysql-connector-java-5.1.38.jar:5.1.38]
... 117 common frames omitted
Thanks.
I was facing a similar problem, try 2 things:
Change spring.datasource.url=jdbc:mysql://ip/database-name to spring.datasource.url=jdbc:mysql://ip/database-name?autoReconnect=true
I was using c3p0 in my application, configuring idleConnectionTestPeriod and preferredTestQuery resolved my issue
<!-- DB Configuration -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc_url}" />
<property name="user" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<property name="driverClass" value="${jdbc_driver_class}" />
<!-- these are C3P0 properties -->
<property name="acquireIncrement" value="1" /> <!-- Determines how many connections at a time c3p0 will try to acquire when the pool is exhausted. -->
<property name="minPoolSize" value="${jdbc_min_pool_size}" />
<property name="maxPoolSize" value="${jdbc_max_pool_size}" />
<property name="maxIdleTime" value="100" /> <!-- Seconds a Connection can remain pooled but unused before being discarded. Zero means idle connections never expire. -->
<!--set this value less then mysql wait_timeout -->
<property name="idleConnectionTestPeriod" value="100"/> <!-- If this is a number greater than 0, C3P0 will test all idle, pooled but unchecked-out connections, every this number of seconds-->
<property name="preferredTestQuery" value="select 1"/> <!--a query used to test connections-->
</bean>
Your property spring.datasource.tomcat.validationInterval seems to do the same. From the error it seems that MySQL wait_timeout in your case is 60,401,089 ms, so the validationInterval seems less than that, but still try reducing it to 100 and see if the error reoccurs. If that doesn't work try configuring c3p0 and using the config I mentioned.

Unable to connect to Impala through Java app using Impala JDBC Driver

I am trying to connect to impala and do a simple select query using JdbcTemplate(). I keep getting the following error:
java.sql.SQLException: [Simba][ImpalaJDBCDriver](500164) Error initialized or created transport for authentication: null.
at com.cloudera.impala.hivecommon.api.HiveServer2ClientFactory.createTransport(Unknown Source)
at com.cloudera.impala.hivecommon.api.HiveServer2ClientFactory.createClient(Unknown Source)
at com.cloudera.impala.hivecommon.core.HiveJDBCConnection.connect(Unknown Source)
at com.cloudera.impala.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
at com.cloudera.impala.jdbc.common.AbstractDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at ProcedureDAOImpl.updateProcedure(ProcedureDAOImpl.java:55)
at MainRunner.procedure1(MainRunner.java:61)
at MainRunner.run(MainRunner.java:33)
at java.util.TimerThread.mainLoop(Unknown Source)
Caused by: com.cloudera.impala.support.exceptions.GeneralException: [Simba][ImpalaJDBCDriver](500164) Error initialized or created transport for authentication: null.
... 11 more
ApplicationContext bean for this connection is defined like this:
<bean id="impalaDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.cloudera.impala.jdbc4.Driver"></property>
<property name="url" value="${jdbc.impala.url}"/>
<property name="username" value="${jdbc.impala.username}"/>
<property name="password" value="${jdbc.impala.password}"/>
</bean>
I tried to connect with DriverManager class and it was successful. But when I try to use dbcp class, it fails. Does anybody have some suggestion on this?
When I got the same error while I was connecting to Impala on DBeaver.
The possible workaround that I found is to keep updating to the latest Impala JDBC driver available.
Note: It works for a while and then I get the same error again. Updating it again solves the problem.

How to resolve "Dialect class not found: org.hibernate.dialect.MYSQLDialect" Exception?

I am very new to hibernate so I am practicing by seeing video tutorial. The link I am following is,
https://www.youtube.com/watch?v=FFMOZY4z6bE&list=PL4AFF701184976B25&index=5
It is simple java project in eclipse. Here I use mysql Data base. Here is my Hibernate.cfg.xml file,
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/hibernatedb
root
root
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MYSQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="com.***.dto.UserDetails"/>
I am getting this kind of error ,
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.MYSQLDialect
at org.hibernate.dialect.resolver.DialectFactory.constructDialect(DialectFactory.java:159)
at org.hibernate.dialect.resolver.DialectFactory.buildDialect(DialectFactory.java:99)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:117)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2863)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2859)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1870)
at com.aurodisplay.hibernate.HibernateTest.main(HibernateTest.java:17)
Caused by: java.lang.ClassNotFoundException: org.hibernate.dialect.MYSQLDialect
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:192)
at org.hibernate.dialect.resolver.DialectFactory.constructDialect(DialectFactory.java:156)
Can any one help me in this.
If you are using a property file, then make sure there is no space at the end of the line.
hibernate.dialect=org.hibernate.dialect.MySQLDialect
The answer is in the question. You've found MySQLDialect in your jar files, but your configuration file tries to use MYSQLDialect. Java is case-sensitive.
Try changing to below
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
If you are using
<org.hibernate.dialect.MySQL8Dialect</property>
simply remove 8 from there
<org.hibernate.dialect.MySQLDialect</property>

How to populate an embedded database (such as hsqldb) on creation

My setup is hibernate / JPA using hsqldb for doing integration tests. I would like to be able to use a sql script to populate some test data into the database.
Essentially I'm looking for an equivalent of Spring's
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:test-data-hsql.sql"/>
</jdbc:initialize-database>
Except for this project using Spring is not an option for me. I've read various hsql articles suggesting this is possible using file mode and pointing the path at the script but I haven't been able to get this working.
My persistence.xml
<persistence-unit name="test-pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>...</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"></property>
<property name="hibernate.connection.username" value="sa"></property>
<property name="hibernate.connection.password" value=""></property>
<property name="hibernate.connection.url" value="jdbc:hsqldb:file:test-data-hsql"></property>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"></property>
<property name="hibernate.hbm2ddl.auto" value="create"></property>
<property name="hibernate.show_sql" value="true"></property>
</properties>
</persistence-unit>
The test-data-hsql.script does get run but there is always an error.
If I include the DDL statements in the script to create I get
Caused by: org.hsqldb.HsqlException: invalid schema name: INFORMATION_SCHEMA
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.SchemaManager.getUserSchemaHsqlName(Unknown Source)
at org.hsqldb.StatementSchema.getResult(Unknown Source)
at org.hsqldb.StatementSchema.execute(Unknown Source)
at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
If I exclude the DDL statements (hoping I can rely on hbm2ddl.auto = create) then I get
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: INFORMATION_SCHEMA.ONETESTUSER
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.SchemaManager.getUserTable(Unknown Source)
at org.hsqldb.scriptio.ScriptReaderText.processStatement(Unknown Source)
at org.hsqldb.scriptio.ScriptReaderText.readLoggedStatement(Unknown Source)
at org.hsqldb.scriptio.ScriptReaderText.readDDL(Unknown Source)
at org.hsqldb.scriptio.ScriptReaderBase.readAll(Unknown Source)
at org.hsqldb.persist.Log.processScript(Unknown Source)
at org.hsqldb.persist.Log.open(Unknown Source)
at org.hsqldb.persist.Logger.open(Unknown Source)
at org.hsqldb.Database.reopen(Unknown Source)
at org.hsqldb.Database.open(Unknown Source)
at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
Does anyone have an example with a working script file or a better way to do this? I'm not necessarily tied to hsqldb if there is an alternative that can support this feature.
Update
The Minimal Script I am using to produce the error has no reference to INFORMATION_SCHEMA
drop table AccessToken if exists
create table AccessToken (id integer generated by default as identity (start with 1), createdAt timestamp not null, lastAccessedAt timestamp, token varchar(255) not null, expirationPolicyId varchar(255) not null, userId varchar(255) not null, primary key (id))
insert into ACCESSTOKEN (id, createdAt, lastAccessedAt, token, expirationPolicyId, userId) values (1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'welcome1', 'oneDayPolicy', 'jtrotter');
You need the DDL statements in the script, otherwise the database is empty and you get the second error.
The problem is in the script, is has reference for mySQL specific meta data schema INFORMATION_SCHEMA. Remove reference to objects in that schema so that the create tables can complete.

Categories

Resources