javahibernatejavafxh2

Hibernate and H2 n JavaFX app, not creating tables


I want to include a database to my JavaFX app. I chose h2 and configured hibernate to use with it. The problem is that it doesnt' create tables from entities like it's supposed to. What I did, I have these dependecies:

<dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>javax.persistence-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>2.1.214</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>6.2.7.Final</version>
    </dependency>

I have this hibernate.cfg.xml configuration file stored in the resources folder:

<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">org.h2.Driver</property>
    <property name="connection.url">jdbc:h2:file:./database
    </property>
    <property name="connection.username">...</property>
    <property name="connection.password">...</property>
    <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property> // setting to create also didn't help
    <mapping class="my.package.model.TestEntity"/>
  </session-factory>
</hibernate-configuration>

TestEntity is annotated with needed annotations like @Entity:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "test_entity")
public class TestEntity {

  @Column(name = "test")
  @Id
  private String test;

}

But it's not working, the database is getting created, but there is no TestEntity table. What could be the problem?


Solution

  • So the problem was with 2 things:

    1. It should import jakarta.persistence.Entity not import javax.persistence.Entity;
    2. Turns out you can't connect to H2 file normally trough IntelliJ idea. So I have to download h2 gui, launch it and only after that I was able to see the content of the database. Also I needed to run h2 with AUTO_SERVER=TRUE.