H2 in-memory database. Table not found - java
I've got a H2 database with URL "jdbc:h2:test". I create a table using CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64));. I then select everything from this (empty) table using SELECT * FROM PERSON. So far, so good.
However, if I change the URL to "jdbc:h2:mem:test", the only difference being the database is now in memory only, this gives me an org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement: SELECT * FROM PERSON [42102-154]. I'm probably missing something simple here, but any help would be appreciated.
DB_CLOSE_DELAY=-1
hbm2ddl closes the connection after creating the table, so h2 discards it.
If you have your connection-url configured like this
jdbc:h2:mem:test
the content of the database is lost at the moment the last connection is closed.
If you want to keep your content you have to configure the url like this
jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
If doing so, h2 will keep its content as long as the vm lives.
Notice the semicolon (;) rather than colon (:).
See the In-Memory Databases section of the Features page. To quote:
By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.
I know this was not your case but I had the same problem because H2 was creating the tables with UPPERCASE names then behaving case-sensitive, even though in all scripts (including in the creation ones) i used lowercase.
Solved by adding ;DATABASE_TO_UPPER=false to the connection URL.
For Spring Boot 2.4+
use
spring.jpa.defer-datasource-initialization=true
in application.properties
Hard to tell. I created a program to test this:
package com.gigaspaces.compass;
import org.testng.annotations.Test;
import java.sql.*;
public class H2Test {
#Test
public void testDatabaseNoMem() throws SQLException {
testDatabase("jdbc:h2:test");
}
#Test
public void testDatabaseMem() throws SQLException {
testDatabase("jdbc:h2:mem:test");
}
private void testDatabase(String url) throws SQLException {
Connection connection= DriverManager.getConnection(url);
Statement s=connection.createStatement();
try {
s.execute("DROP TABLE PERSON");
} catch(SQLException sqle) {
System.out.println("Table not found, not dropping");
}
s.execute("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
PreparedStatement ps=connection.prepareStatement("select * from PERSON");
ResultSet r=ps.executeQuery();
if(r.next()) {
System.out.println("data?");
}
r.close();
ps.close();
s.close();
connection.close();
}
}
The test ran to completion, with no failures and no unexpected output. Which version of h2 are you running?
When opening the h2-console, the JDBC URL must match the one specified in the properties:
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.h2.console.enabled=true
Which seems obvious, but I spent hours figuring this out..
The H2 in-memory database stores data in memory inside the JVM. When the JVM exits, this data is lost.
I suspect that what you are doing is similar to the two Java classes below. One of these classes creates a table and the other tries to insert into it:
import java.sql.*;
public class CreateTable {
public static void main(String[] args) throws Exception {
DriverManager.registerDriver(new org.h2.Driver());
Connection c = DriverManager.getConnection("jdbc:h2:mem:test");
PreparedStatement stmt = c.prepareStatement("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
stmt.execute();
stmt.close();
c.close();
}
}
and
import java.sql.*;
public class InsertIntoTable {
public static void main(String[] args) throws Exception {
DriverManager.registerDriver(new org.h2.Driver());
Connection c = DriverManager.getConnection("jdbc:h2:mem:test");
PreparedStatement stmt = c.prepareStatement("INSERT INTO PERSON (ID, FIRSTNAME, LASTNAME) VALUES (1, 'John', 'Doe')");
stmt.execute();
stmt.close();
c.close();
}
}
When I ran these classes one after the other, I got the following output:
C:\Users\Luke\stuff>java CreateTable
C:\Users\Luke\stuff>java InsertIntoTable
Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement:
INSERT INTO PERSON (ID, FIRSTNAME, LASTNAME) VALUES (1, 'John', 'Doe') [42102-154]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
at org.h2.message.DbException.get(DbException.java:167)
at org.h2.message.DbException.get(DbException.java:144)
...
As soon as the first java process exits, the table created by CreateTable no longer exists. So, when the InsertIntoTable class comes along, there's no table for it to insert into.
When I changed the connection strings to jdbc:h2:test, I found that there was no such error. I also found that a file test.h2.db had appeared. This was where H2 had put the table, and since it had been stored on disk, the table was still there for the InsertIntoTable class to find.
One reason can be that jpa tries to insert data before creating table structure, in order to solve this problem , insert this line in application.properties :
spring.jpa.defer-datasource-initialization=true
I have tried to add
jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
However, that didn't helped. On the H2 site, I have found following, which indeed could help in some cases.
By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.
However, my issue was that just the schema supposed to be different than default one. So insted of using
JDBC URL: jdbc:h2:mem:test
I had to use:
JDBC URL: jdbc:h2:mem:testdb
Then the tables were visible
Solved by creating a new src/test/resources folder + insert application.properties file, explicitly specifying to create a test dbase :
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
I had the same problem and changed my configuration in application-test.properties to this:
#Test Properties
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
And my dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.198</version>
<scope>test</scope>
</dependency>
And the annotations used on test class:
#RunWith(SpringRunner.class)
#DataJpaTest
#ActiveProfiles("test")
public class CommentServicesIntegrationTests {
...
}
I was trying to fetch table meta data, but had the following error:
Using:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
DatabaseMetaData metaData = connection.getMetaData();
...
metaData.getColumns(...);
returned an empty ResultSet.
But using the following URL instead it worked properly:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";
There was a need to specify: DATABASE_TO_UPPER=false
I have tried adding ;DATABASE_TO_UPPER=false parameter, which it did work in a single test, but what did the trick for me was ;CASE_INSENSITIVE_IDENTIFIERS=TRUE.
At the end I had: jdbc:h2:mem:testdb;CASE_INSENSITIVE_IDENTIFIERS=TRUE
Moreover, the problem for me was when I upgraded to Spring Boot 2.4.1.
I came to this post because I had the same error.
In my case the database evolutions weren't been executed, so the table wasn't there at all.
My problem was that the folder structure for the evolution scripts was wrong.
from: https://www.playframework.com/documentation/2.0/Evolutions
Play tracks your database evolutions using several evolutions script. These scripts are written in plain old SQL and should be located in the conf/evolutions/{database name} directory of your application. If the evolutions apply to your default database, this path is conf/evolutions/default.
I had a folder called conf/evolutions.default created by eclipse. The issue disappeared after I corrected the folder structure to conf/evolutions/default
Had the exact same issue, tried all the above, but without success.
The rather funny cause of the error was that the JVM started too fast, before the DB table was created (using a data.sql file in src.main.resources). So I've put a Thread.sleep(1000) timer to wait for just a second before calling "select * from person".
Working flawlessly now.
application.properties:
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
data.sql:
create table person
(
id integer not null,
name varchar(255) not null,
location varchar(255),
birth_date timestamp,
primary key(id)
);
insert into person values (
10001, 'Tofu', 'home', sysdate()
);
PersonJdbcDAO.java:
public List<Person> findAllPersons(){
return jdbcTemplate.query("select * from person",
new BeanPropertyRowMapper<Person>(Person.class));
}
main class:
Thread.sleep(1000);
logger.info("All users -> {}", dao.findAllPersons());
I have tried the above solution,but in my case as suggested in the console added the property DB_CLOSE_ON_EXIT=FALSE, it fixed the issue.
spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false;DB_CLOSE_ON_EXIT=FALSE
I might be a little late to the party, but I faced exactly the same error and I tried pretty much every solution mentioned here and on other websites such as DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1; DB_CLOSE_ON_EXIT=FALSE; IGNORECASE=TRUE
But nothing worked for me.
What worked for me was renaming data.sql to import.sql
I found it here - https://stackoverflow.com/a/53179547/8219358
Or
For Spring Boot 2.4+ use spring.jpa.defer-datasource-initialization=true in application.properties (mentioned here - https://stackoverflow.com/a/68086707/8219358)
I realize other solutions are more logical but none of them worked for me and this did.
Had similar problem
Solution was to add the following to application.properties
spring.jpa.defer-datasource-initialization=true
<bean id="benchmarkDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
I found it working after adding the dependency of Spring Data JPA -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Add H2 DB configuration in application.yml -
spring:
datasource:
driverClassName: org.h2.Driver
initialization-mode: always
username: sa
password: ''
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
h2:
console:
enabled: true
path: /h2
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: none
The issue can also happen if there was error while generating the table.
If the entities use any features which are not supported by H2 (for example, specifying a non-standard columnDefinition), the schema generation will fail and test will continue without the database generated.
In this case, somewhere in the logs you will find this:
WARN ExceptionHandlerLoggedImpl: GenerationTarget encountered exception accepting command :
Error executing DDL "create table ..." via JDBC Statement
In my case missing table error was happening during jpa test, table was created by schem.sql file, problem was fixed after puting #org.springframework.transaction.annotation.Transactional on test
In my case, I had used the special keywords for my column-names in the table, H2 Database. If you're using different databases avoid those special keywords across different databases. Spring & Hibernate isn't smart enough to tell you exactly which column names are prohibited or where the exact error is in the table-creation.
Keywords such as;
desc, interval, metric
To resolve the issues I was experiencing, I renamed those fields to:
descr, time_interval, time_metric
http://www.h2database.com/html/advanced.html
Use the same in applications.properties file
spring.jpa.show-sql=true
spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false
DB_CLOSE_ON_EXIT=FALSE
spring.data.jpa.repositories.bootstrap-mode=default
spring.h2.console.enabled=true spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.defer-datasource-initialization=true
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
in my case, my table name was user but from H2 2.1.212 user is reserved so couldn't make the table
changed table name users by #Table(name="users") and
datasource:
url: jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1;
and it works now
I suspect the database you opened is a brand new db, not your application db. This is because:
H2 in-memory database by default is private to the JVM and the classloader. It cannot be connected from another process/with TCP from same machine/from another machine; that's why all the guides suggest using H2 console, because that's within the same JVM of your application so it can access the database(however, my H2 console shipped with Spring 2.6 is not working, I need to find another way)
H2 database can be launched in server mode, but ";AUTO_SERVER=true" does not work with in-memory db; it only can be added to the URL when you use a file based db; and to visit it you need to use absolute path to the db file, which is not portable and is ugly; additionally, auto-generation of tables are not done when you use a file so you need to create an init.sql to create tables. AND, when you connect H2 still tells you that you need server mode, because there is already one connection to the db(your app) and to allow 1+ connection, you need server mode
So in both cases you need server mode. How?
In Spring you need to create the DB as a bean(thanks to How to enable H2 Database Server Mode in Spring Boot); put this into a #Configuration and you are done:
#Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "1234"); // or any other port
}
Your db url:
spring:
datasource:
url: jdbc:h2:mem:test
driver-class-name: org.h2.Driver
port: 1234
username: sa
password: sa
That's all. You can connect with H2 console, or DB Navigator, or other tools along with your app right now. The connection string is:
jdbc:h2:tcp://localhost:1234/mem:test
Related
HSQL database user lacks privilege or object not found error
I am trying to use hsqldb-2.3.4 to connect from Spring applicastion. I created data base using the following details Type : HSQL Database Engine Standalone Driver: org.hsqldb.jdbcDriver URL: jdbc:hsqldb:file:mydb UserName: SA Password: SA I created a table named ALBUM under "MYDB" schema In spring configuration file: <bean id="jdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dbcpDataSource" /> </bean> <bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.hsqldb.jdbcDriver" /> <property name="url" value="jdbc:hsqldb:file:mydb" /> <property name="username" value="SA" /> <property name="password" value="SA" /> </bean> And in my spring controller I am doing jdbcTemplate.query("SELECT * FROM MYDB.ALBUM", new AlbumRowMapper()); And It gives me exception: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM MYDB.ALBUM]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ALBUM org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) javax.servlet.http.HttpServlet.service(HttpServlet.java:622) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) If I execute same query through SQL editor of hsqldb it executes fine. Can you please help me with this.
As said by a previous response there is many possible causes. One of them is that the table isn't created because of syntax incompatibility. If specific DB vendor syntax or specific capability is used, HSQLDB will not recognize it. Then while the creation code is executed you could see that the table is not created for this syntax reason. For exemple if the entity is annoted with #Column(columnDefinition = "TEXT") the creation of the table will fail. There is a work around which tell to HSQLDB to be in a compatible mode for pgsl you should append your connection url with that "spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true" and for mysql with "spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_mys=true" oracle "spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_ora=true" note there is variant depending on your configuration it could be hibernate.connection.url= or spring.datasource.url= for those who don't use the hibernate schema creation but a SQL script you should use this kind of syntax in your script SET DATABASE SQL SYNTAX ORA TRUE; It will also fix issues due to vendor specific syntax in SQL request such as array_agg for posgresql Nota bene : The the problem occurs very early when the code parse the model to create the schema and then is hidden in many lines of logs, then the unitTested code crash with a confusing and obscure exception "user lacks privilege or object not found error" which does not point the real problem at all. So make sure to read all the trace from the beginning and fix all possible issues
If you've tried all the other answers on this question, then it is most likely that you are facing a case-sensitivity issue. HSQLDB is case-sensitive by default. If you don't specify the double quotes around the name of a schema or column or table, then it will by default convert that to uppercase. If your object has been created in uppercase, then you are in luck. If it is in lowercase, then you will have to surround your object name with double quotes. For example: CREATE MEMORY TABLE "t1"("product_id" INTEGER NOT NULL) To select from this table you will have to use the following query select "product_id" from "t1"
user lacks privilege or object not found can have multiple causes, the most obvious being you're accessing a table that does not exist. A less evident reason is that, when you run your code, the connection to a file database URL actually can create a DB. The scenario you're experiencing might be you've set up a DB using HSQL Database Manager, added tables and rows, but it's not this specific instance your Java code is using. You may want to check that you don't have multiple copies of these files: mydb.log, mydb.lck, mydb.properties, etc in your workspace. In the case your Java code did create those files, the location depends on how you run your program. In a Maven project run inside Netbeans for example, the files are stored alongside the pom.xml.
I had the error user lacks privilege or object not found while trying to create a table in an empty in-memory database. I used spring.datasource.schema and the problem was that I missed a semicolon in my SQL file after the "CREATE TABLE"-Statement (which was followed by "CREATE INDEX").
I had similar issue with the error 'org.hsqldb.HsqlException: user lacks privilege or object not found: DAYS_BETWEEN' turned out DAYS_BETWEEN is not recognized by hsqldb as a function. use DATEDIFF instead. DATEDIFF ( <datetime value expr 1>, <datetime value expr 2> )
When running a HSWLDB server. for example your java config file has: hsql.jdbc.url = jdbc:hsqldb:hsql://localhost:9005/YOURDB;sql.enforce_strict_size=true;hsqldb.tx=mvcc check to make sure that your set a server.dbname.#. for example my server.properties file: server.database.0=eventsdb server.dbname.0=eventsdb server.port=9005
I was inserting the data in hsql db using following script INSERT INTO Greeting (text) VALUES ("Hello World"); I was getting issue related to the Hello World object not found and HSQL database user lacks privilege or object not found error which I changed into the below script INSERT INTO Greeting (text) VALUES ('Hello World'); And now it is working fine.
Add these two extra properties: spring.jpa.hibernate.naming.implicit-strategy= org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl spring.jpa.hibernate.naming.physical-strategy= org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
I bumped into kind of the same problem recently. We are running a grails application and someone inserted a SQL script into the BootStrap file (that's the entry point for grails). That script was supposed to be run only in the production environment, however because of bad logic it was running in test as well. So the error I got was: User lacks privilege or object not found: without any more clarification... I just had to make sure the script was not run in the test environment and it fixed the problem for me, though it took me 3 hours to figure it out. I know it is very, very specific issue but still if I can save someone a couple of hours of code digging that would be great.
I was having the same mistake. In my case I was forgetting to put the apas in the strings. I was doing String test = "inputTest"; The correct one is String test = "'inputTest'"; The error was occurring when I was trying to put something in the database connection.createStatement.execute("INSERT INTO tableTest values(" + test +")"; In my case, just put the quotation marks ' to correct the error.
In my case the error occured because i did NOT put the TABLE_NAME into double quotes "TABLE_NAME" and had the oracle schema prefix. Not working: SELECT * FROM FOOSCHEMA.BAR_TABLE Working: SELECT * FROM "BAR_TABLE"
had this issue with concatenating variables in insert statement. this worked // var1, var3, var4 are String variables // var2 and var5 are Integer variables result = statement.executeUpdate("INSERT INTO newTable VALUES ('"+var1+"',"+var2+",'"+var3+"','"+var4+"',"+var5 +")");
In my case the issue was caused by the absence (I'd commented it out by mistake) of the following line in persistence.xml: <property name="hibernate.hbm2ddl.auto" value="update"/> which prevented Hibernate from emitting the DDL to create the required schema elements... (different Hibernate wrappers will have different mechanisms to specify properties; I'm using JPA here)
I had this error while trying to run my application without specifying the "Path" field in Intellij IDEA data source (database) properties. Everything else was configured correctly. I was able to run scripts in IDEA database console and they executed correctly, but without giving a path to the IDEA, it was unable to identify where to connect, which caused errors.
You have to run the Database in server mode and connect.Otherwise it wont connect from external application and give error similar to user lacks privilege. Also change the url of database in spring configuration file accordingly when running DB in server mode. Sample command to run DB in server mode $java -cp lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:data/mydb --dbname.0 Test Format of URL in configuration file jdbc:hsqldb:hsql://localhost/Test
In my case, one of the columns had the name 'key' with the missing #Column(name = "key") annotation so that in the logs you could see the query that created the table but in fact it was not there. So be careful with column names
For what it's worth - I had this same problem. I had a column named 'TYPE', which I renamed to 'XTYPE' and a column named ORDER which I renamed to 'XORDER' and the problem went away.
Yet another reason could be a misspelt field name. If your actual table has an id column named albumid and you'd used album_id, then too this could occur. As another anwer remarked, case differences in field names too need to be taken care of.
I faced the same issue and found there was more than one PersistenceUnit (ReadOnly and ReadWrite) , So the tables in HSQLDDB created using a schema from one persistence unit resulted in exception(HSQL database user lacks privilege or object not found error) being thrown when accessed from other persistence unit .It happens when tables are created from one session in JPA and accessed from another session
In my case the table MY_TABLE was in the schema SOME_SCHEMA. So calling select/insert etc. directly didn't work. To fix: add file schema.sql to the resources folder in this file add the line CREATE SCHEMA YOUR_SCHEMA_NAME;
Hibernate and DB2- gives out an ERROR: util.JDBCExceptionReporter while inserting into or deleting from the table
My insert code in the DAO: public void add(){ Books a=new Books(); a.setId("213"); a.setName("The DaVinci Code"); a.setAuthor("Dan Brown"); getSession().save(a); } I am trying insert or delete a record from the database DB2. But it gives me the following error: ERROR util.JDBCExceptionReporter - [SQL7008] (TABLE name) not valid for operation. ERROR def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.GenericJDBCException: could not insert: I also heard something about journaling in the net but not sure about it. I have no idea how to solve the problem. Please help!
When using DB2 as database, you have to journal a table before any update or insert within a transaction. If you try to make it within a transaction and it's not being journalled, it shows you code SQL7008. Hibernate has a default propery of autocommit which is false if you set it to true it would work, but it's not recommended to do it since you will not be able to control the transactions and commit only if everything works. <property name="hibernate.connection.autocommit" value="true"/> (Not recommended) So, the idea would be you to fix it in your database and set the table as journalled.
Force Hibernate To Create Tables After Dropping and Recreating database
I am developing a web application with java 2 ee. I also use hibernate and mysql. in order to restore the backup file, in some point in my application i need to drop the current database and recreate it, i do it as follow : Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=user&password=pass"); Statement statement = (Statement) conn.createStatement(); statement.executeUpdate("DROP DATABASE tcs;"); statement.executeUpdate("CREATE DATABASE tcs charset=utf8 collate=utf8_persian_ci;"); after dropping and recreating i need to initialize database with default user (spring security user) User admin = new User(); UserAuthority ROLE_USER = new UserAuthority("ROLE_USER"); ROLE_USER.save(); admin.addUserAuthority(ROLE_USER); admin.setEnabled(true); admin.save(); but at the last line application throws this exception Hibernate: insert into roles (authority) values (?) [DEBUG][16:19:17,734] [http-bio-8080-exec-10] NewPooledConnection:367 com.mchange.v2.c3p0.impl.NewPooledConnection#bcbe33a handling a throwable. com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'tcs.roles' doesn't exist i know hibernate creates tables at startup but in this case it fails to recreate the tables after a drop/recreate , so how can i force hibernate to create tables again? or hypothetically is there something like Hibernate.createTable(Class) ?
You need to add the following property to your configuration: Drop and Recreate everytime SessionFactory is created and destroyed: <property name="hbm2ddl.auto">create-drop</property> Other possible options: validate: validate the schema, makes no changes to the database. update: update the schema. create: creates the schema, destroying previous data.
for future googlers : it was so simple after all , i just needed to build session factory so i added this line and it worked like charm : new Configuration().configure().buildSessionFactory(); note that buildSessionFactory() is deprecated in hibernate 4 but i guess you can use the code here to do the same.
JDBC Change Default Schema
I'm trying to connect to a sql server 2005 database via JDBC. I get the error: com.microsoft.sqlserver.jdbc.SQLServerException: The SELECT permission was denied on the object 'MyTable', database 'MyDatabase', schema 'dbo'. The schema I use to connect is "MyUser". How do I connect using MyUser as opposed to dbo? Thanks!
To clear things up: You connect to SQL Server using a user, not a schema. You don't say what version of SQL Server you're connecting to, but it used to be the case that the two were equivalent. As of 2005+, that is no longer true. dbo is the default schema (think of it as a namespace); what the error message is telling you is the user you are connecting with (If I understand correctly, that's MyUser) does not have permission to SELECT from the MyTable table, which is part of the dbo schema in the MyDatabase database. The first thing to do is confirm whether or not the user you're connecting with does or does not have SELECT permissions on that table. The second thing to do is, if it doesn't, either give MyUser that permission or use a different user to perform the SELECT statement.
i found that you have to specify your schema in your POJOS definitions. In my case I got the same trouble using JPA (Entities / Annotations) and I realized that specifing the schema property in the #Table annotation works. for example: #Table(name = "address", **schema="*dbo*"**, catalog = "petcatalog") I hope this helps you.
HSQLDB and Hibernate/JPA - not persisting to disk?
Something of an novice with HSQL and Hibernate... em.getTransaction().begin(); for (Activity theActivity : activities) { em.persist(theActivity); } em.getTransaction().commit(); em.close(); followed by... EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); System.out.println("QUERY:: " + em.createQuery("SELECT COUNT(*) FROM " + Activity.class.getName()).getSingleResult() .toString()); em.getTransaction().commit(); Prints 25000 (the number of Activity objects in activities). But when I run this test again, the number of objects in the count(*) doesn't increase (and is 0 at the beginning of the program). So the objects aren't getting durably written. This is my hsqldb connection string: name="hibernate.connection.url" value="jdbc:hsqldb:file:data/cmon" so it's not an in-memory database as far as I know... Does anyone have any ideas why the objects aren't getting persisted beyond a single JVM session? Happy to supply more information but there's so much state associated with Hibernate / JPA / HSQL that it's not clear exactly what is pertinent.
Does anyone have any ideas why the objects aren't getting persisted beyond a single JVM session? HSQLDB doesn't write changes immediately to disk after a commit (see "WRITE DELAY"), HSQLDB is not Durable by default (that's from where "performances" are coming from). Either try to set the connection property shutdown=true in the connection string to get the changes written when the last connection will end. jdbc:hsqldb:file:data/cmon;shutdown=true If it doesn't help, try to set the WRITE DELAY to 0 (or false). If you're using HSQLDB 1.8.x, use the SQL command: SET WRITE_DELAY 0 If you're using HSQLDB 2.0.x, you can now also use a connection property hsqldb.write_delay: jdbc:hsqldb:file:data/cmon;hsqldb.write_delay=false
The solution is : <property name="dialect">org.hibernate.dialect.HSQLDialect</property> in hibernate.cfg.xml This is rest of my configuration: Libs: HsqlDb 2.0.0 Hibernate 3.5.6 Url: <property name="connection.url">jdbc:hsqldb:file:data/mydb;shutdown=true;hsqldb.write_delay=false;</property>
Did you set hibernate.hbm2ddl.auto to create-drop in your persistence.xml? This drops your tables and re-creates them on every startup. You can set it to update instead, or if you want to manage the schema yourself, then set it to validate.
I was using HSQL DB version 2.2.5. I tried above approaches i.e. setting shutdown=true and hsqldb.write_delay=false It did not work. As suggested in some blog, I added statement org.hsqldb.DatabaseManager.closeDatabases(0); after transaction commit. But it did not work. HSQL DB version 2.2.9 seems better than this. With one workaround it solves this problem. To handle above problem take following steps :- 1) hsqldb.jar from lib of HSQL DB version 2.2.9 2) In hibernate config xml just specify URL I am using HSQL file-based database. <property name="hibernate.connection.url">jdbc:hsqldb:file:D:\JavaProj\TmpDBLocation\myKauDB</property> 3) In your program at the end write statement org.hsqldb.DatabaseManager.closeDatabases(0); Now run the hibernate program that commits the data to DB. Check HSQL DB by opening it in standalone mode and with URL jdbc:hsqldb:file:D:\JavaProj\TmpDBLocation\myKauDB You should see your changes persisted in DB.
Simply close your EntityManagerFactory with HSQL in filemode, after the commit to really persist datas...
Closing sessionfactory worked for me.