Skip to content
Advertisement

h2 database persists data but resets on application start

I have a basic test for an embedded database that I’m trying to get working for a java project. As it stands now I am able to save rows to the database with my entity repository object, and after the app finishes running, I can connect to the database with intellij and see those rows are still there. But then, if I comment out the save methods and run it again, when I check the database after it finishes, the database is empty.

Entity

package closet.utilities.entities;

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

@Entity
@Table(name = "outfits")
public class Outfit {

    @Id
    @Column(name = "id")
    String id;

    @Column(name = "inv_name")
    String invName;

    @Column(name = "display_name")
    String displayName;

    @Column(name = "owner")
    String owner;

    public Outfit() {
    }

    public Outfit(String id, String invName, String displayName, String owner) {
        this.id = id;
        this.invName = invName;
        this.displayName = displayName;
        this.owner = owner;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getInvName() {
        return invName;
    }

    public void setInvName(String invName) {
        this.invName = invName;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    @Override
    public String toString() {
        return "Outfit{" +
                "id='" + id + ''' +
                ", invName='" + invName + ''' +
                ", displayName='" + displayName + ''' +
                ", owner='" + owner + ''' +
                '}';
    }
}

Repository

package closet.utilities.repositories;

import closet.utilities.entities.Outfit;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;

public class OutfitRepository {

    private EntityManager entityManager;

    public OutfitRepository(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public Optional<Outfit> findById(String id) {
        Outfit outfit = entityManager.find(Outfit.class, id);
        return outfit != null ? Optional.of(outfit) : Optional.empty();
    }

    public List<Outfit> findAll() {
        return entityManager.createQuery("from Outfit").getResultList();
    }

    public Optional<Outfit> save(Outfit outfit) {
        try {
            entityManager.getTransaction().begin();
            entityManager.persist(outfit);
            entityManager.getTransaction().commit();
            return Optional.of(outfit);
        } catch (Exception e) {
            // TODO logging
            e.printStackTrace();
        }
        return Optional.empty();
    }
}

main method

package closet.utilities;

import closet.utilities.entities.Outfit;
import closet.utilities.repositories.OutfitRepository;
import org.hibernate.Session;
import org.hibernate.Transaction;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class Runnable {

    public static void main(String[] args) {

        // Create our entity manager
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("closet");
        EntityManager entityManager = entityManagerFactory.createEntityManager();


        Outfit outfit = new Outfit("Ramesh", "Fadatare", "rameshfadatare@javaguides.com", "");
        Outfit outfit1 = new Outfit("John", "Cena", "john@javaguides.com", "");
        OutfitRepository outfitRepository = new OutfitRepository(entityManager);
        //outfitRepository.save(outfit);
        //outfitRepository.save(outfit1);

        List<Outfit> outfits = outfitRepository.findAll();

        for (Outfit o : outfits) {
            System.out.println(o.getInvName());
        }

    }
}

persistence.xml

<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                      http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">

    <persistence-unit name="closet" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>closet.utilities.entities.Outfit</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
            <property name="javax.persistence.jdbc.url"    value="jdbc:h2:./data/closet" />
            <property name="javax.persistence.jdbc.user" value="sa" />
            <property name="javax.persistence.jdbc.password" value="" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop" />
            <property name="show_sql" value="true"/>
            <property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
        </properties>
    </persistence-unit>
</persistence>

hibernate.cfg.xml

<!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>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:./data/closet</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>
        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create-drop</property>
        <!-- dbcp connection pool configuration -->
        <property name="hibernate.dbcp.initialSize">5</property>
        <property name="hibernate.dbcp.maxTotal">20</property>
        <property name="hibernate.dbcp.maxIdle">10</property>
        <property name="hibernate.dbcp.minIdle">5</property>
        <property name="hibernate.dbcp.maxWaitMillis">-1</property>
        <mapping class="closet.utilities.entities.Outfit" />
    </session-factory>
</hibernate-configuration>

I’m just following this tutorial here as a guide to just figure out how to get it all working. I can’t see what I’m doing wrong based on that.

Advertisement

Answer

You use:

<property name="hbm2ddl.auto">create-drop</property>

As it is stated in the documentation:

create-drop

Drop the schema and recreate it on SessionFactory startup. Additionally, drop the schema on SessionFactory shutdown.

So, this is expected behaviour.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement