架构未在 hbmddl.auto = create.drop 上删除

Posted

技术标签:

【中文标题】架构未在 hbmddl.auto = create.drop 上删除【英文标题】:Schema is not dropped on hbmddl.auto = create.drop 【发布时间】:2011-10-08 17:29:27 【问题描述】:

我正在使用hbmddl.auto设置在hibernate配置文件中创建并使用它以网络模式连接到derby数据库(未嵌入,不知道是否相关)。

这是我的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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
        <property name="connection.url">jdbc:derby://localhost:1527/HibernateDb;create=true</property>
        <property name="connection.username">admin</property>
        <property name="connection.password">admin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.DerbyDialect</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-drop</property>

        <!-- Names the annotated entity class -->
        <mapping class="org.asif.javabrains.dto.UserDetails"/>

    </session-factory>

</hibernate-configuration>

但是当我运行使用这个又名服务类的 java 程序时,我似乎没有删除数据库并重新创建它。正如评论所说(我从休眠示例中获取了配置文件)。

~~~~更新~~~~

我得出的结论是 hbm2ddl 没有根据以下行为删除架构

我有 2 个类如下所示

@Entity
public class UserDetails 

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int userId;
    private String userName;

    @OneToMany
    @JoinTable(name="USER_VEHICLE",
               joinColumns=@JoinColumn(name="USER_ID"),
               inverseJoinColumns = @JoinColumn(name="VEHICLE_ID")
    )    
    private Collection<Vehicle> vehicles = new ArrayList<Vehicle>() ;

        /* getters and setters */

@Entity
public class Vehicle 
    @Id @GeneratedValue
    private int vehicleId;
    private String vehicleName;
    @ManyToOne
    @JoinColumn(name="USER_ID")
    private UserDetails user;

        /* getters and setters */

对应的hibernate配置是

 <!--boiler plate-->

   <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <!-- Names the annotated entity class -->
    <mapping class="org.asif.javabrains.dto.UserDetails"/>
    <mapping class="org.asif.javabrains.dto.Vehicle"/>

  <!--boiler plate-->

现在当我将上述类更改为

  @Entity
    public class UserDetails 

        @Id @GeneratedValue(strategy=GenerationType.AUTO)
        private int userId;
        private String userName;

        @OneToMany(mappedBy="user")
        private Collection<Vehicle> vehicles = new ArrayList<Vehicle>() ;
    //rest is same

@Entity
public class Vehicle 
    @Id @GeneratedValue
    private int vehicleId;
    private String vehicleName;
    @ManyToOne
    @JoinColumn(name="USER_ID")
    private UserDetails user;
      //rest is same

以下内容打印到控制台

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.
Hibernate: insert into UserDetails (userId, userName) values (default, ?)
Hibernate: values identity_val_local()
Hibernate: insert into Vehicle (vehicleId, USER_ID, vehicleName) values (default, ?, ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [org.asif.javabrains.dto.Vehicle]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:64)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
    at org.asif.javabrains.hibernate.HibernateTest.main(HibernateTest.java:33)
Caused by: java.sql.SQLSyntaxErrorException: 'USER_ID' is not a column in table or VTI 'ADMIN.VEHICLE'.
    at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
    at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
    at org.apache.derby.client.am.Connection.prepareStatement(Unknown Source)
    at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:534)
    at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:116)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:54)
    ... 16 more
Caused by: org.apache.derby.client.am.SqlException: 'USER_ID' is not a column in table or VTI 'ADMIN.VEHICLE'.
    at org.apache.derby.client.am.Statement.completeSqlca(Unknown Source)
    at org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
    at org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
    at org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
    at org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
    at org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
    at org.apache.derby.client.am.Statement.readPrepareDescribeOutput(Unknown Source)
    at org.apache.derby.client.am.PreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
    at org.apache.derby.client.am.PreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
    at org.apache.derby.client.am.PreparedStatement.prepare(Unknown Source)
    at org.apache.derby.client.am.Connection.prepareStatementX(Unknown Source)
    ... 20 more

当我手动删除表并再次执行时,这似乎消失了。是什么导致了这种行为。

【问题讨论】:

【参考方案1】:

该评论实际上是不正确的。由于quite a long time ago,“create-drop”与“create”相比的真正行为是前者在 SessionFactory 关闭时删除模式。 “创建”本身按照评论所说的那样做,即删除模式并在启动时重新创建它。为了验证,将“org.hibernate”日志记录设置为跟踪将显示使用“create”或“create-drop”,架构被删除,然后在启动时创建:

INFO - Running hbm2ddl schema export
DEBUG - import file not found: /import.sql
INFO - exporting generated schema to database
TRACE - total checked-out connections: 0
TRACE - using pooled JDBC connection, pool size: 0
DEBUG - alter table Bar drop constraint FK103F39E150191
DEBUG - Unsuccessful: alter table Bar drop constraint FK103F39E150191
DEBUG - Table "BAR" not found; SQL statement:
alter table Bar drop constraint FK103F39E150191 [42102-149]
DEBUG - drop table Bar if exists
DEBUG - drop table Foo if exists
DEBUG - create table Bar (id integer generated by default as identity, foo_id integer, primary key (id))
DEBUG - create table Foo (id integer generated by default as identity, primary key (id))
DEBUG - alter table Bar add constraint FK103F39E150191 foreign key (foo_id) references Foo
INFO - schema export complete

但是,在关闭时 (SessionFactory.close()),“创建”会给出

INFO - closing
INFO - cleaning up connection pool: jdbc:h2:file:D:/dev/projects/testbed/test-db-for-hibernate-create-drop

而使用“create-drop”,您会看到

INFO - closing
INFO - Running hbm2ddl schema export
DEBUG - import file not found: /import.sql
INFO - exporting generated schema to database
TRACE - total checked-out connections: 0
TRACE - using pooled JDBC connection, pool size: 0
DEBUG - alter table Bar drop constraint FK103F39E150191
DEBUG - drop table Bar if exists
DEBUG - drop table Foo if exists
INFO - schema export complete
TRACE - returning connection to pool, pool size: 1
INFO - cleaning up connection pool: jdbc:h2:file:D:/dev/projects/testbed/test-db-for-hibernate-create-drop

你可以自己试试:

git clone git@github.com:zzantozz/testbed tmp
cd tmp
mvn compile exec:java -Dexec.mainClass=rds.hibernate.Main -pl hibernate-create-drop

【讨论】:

感谢您的评论。我会尝试的,但我有 hbm2ddl 指向最初创建,但后来由于我上面描述的行为将其更改为 create-drop。 但我认为问题正在发生,可能是因为我正在尝试不同的注释来创建对象之间的关系,但每次都是如此。正如我在编辑中描述的那样。 @Shishya:该输出很难确定没有创建和/或删除架构。您需要正确配置 SLF4J 并查看 Hibernate 启动的输出。那里可能有您遗漏的错误。【参考方案2】:

你可能忘了打电话给sessionFactory.close(),就像我犯的错误一样。突然退出并不优雅。

使用create-drop,当SessionFactory 显式关闭时,数据库架构将被删除。

——Hibernate Community Documentation, Chapter 3. Configuration.

【讨论】:

以上是关于架构未在 hbmddl.auto = create.drop 上删除的主要内容,如果未能解决你的问题,请参考以下文章

未在指定架构中创建表

XML实例禁止未在架构中定义的元素

Xcode 11 未在 SwiftUI 中显示对象库

获取未在 FormType 中声明的字段的值

PayPal REST SDK 未在 execute() 上返回正确状态

Axios未在请求中放置原始标头