h2 数据库保留数据但在应用程序启动时重置

Posted

技术标签:

【中文标题】h2 数据库保留数据但在应用程序启动时重置【英文标题】:h2 database persists data but resets on application start 【发布时间】:2021-01-25 21:30:07 【问题描述】:

我有一个嵌入式数据库的基本测试,我正在尝试为一个 java 项目工作。就目前而言,我可以使用我的实体存储库对象将行保存到数据库中,并且在应用程序完成运行后,我可以使用 intellij 连接到数据库并查看这些行仍然存在。但是,如果我注释掉save方法并再次运行它,当我在它完成后检查数据库时,数据库是空的。

实体

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 + '\'' +
                '';
    

存储库

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();
    

主要方法

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>

我只是在此处关注this tutorial 作为指南,以了解如何使其全部正常工作。基于此,我看不出我做错了什么。

【问题讨论】:

【参考方案1】:

你使用:

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

正如documentation中所述:

创建删除

删除架构并在 SessionFactory 启动时重新创建它。此外,在 SessionFactory 关闭时删除架构。

所以,这是预期的行为。

【讨论】:

谢谢。我将其更改为“无”并且它起作用了。

以上是关于h2 数据库保留数据但在应用程序启动时重置的主要内容,如果未能解决你的问题,请参考以下文章

内省 H2 内存数据库

H2 内存数据库未在 weblogic 中显示控制台,但在 Tomcat 中显示

设置 H2 数据库时出错

H2 在第一次访问数据库时间歇性地遇到 ***Error

Primefaces 数据表重置分页

当我们使用 appium 重新启动应用程序时,无法在 ios 11.2 中限制应用程序重置数据