当前位置: 首页 > 面试题库 >

模式未放在hbmddl.auto = create.drop上

龙涵蓄
2023-03-14
问题内容

我正在使用hbmddl.autoset在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程序时,我似乎并没有删除数据库并重新创建它。如评论所述(我从hibernate示例中获取了配置文件)。

~~更新 ~~

我得出结论,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

当我手动删除表并再次执行时,这似乎消失了。是什么引起了这种现象。


问题答案:

该评论实际上是不正确的。从很久以前开始,与“创建”相比,“创建-
删除”的真实行为是前者在关闭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


 类似资料:
  • 我无法在hadoop fs-ls/命令上查看HDFS中的文件,我想这是因为name节点没有运行。我尝试了格式化namenode,并将core-site.xml中的端口更改为不同的值,但我的JPS没有列出namenode。 下面是这些文件:1)core-site.xml 3)mapred-site.xml JPS输出为: 21043作业跟踪器 20839数据阳极

  • 我最近建立了以下网站。该网站在所有图像上使用img srcset。 在调试过程中,我发现当在主页上的纵向和横向模式之间切换时,顶部全宽图像并没有像它应该的那样填充视口。如果以横向模式刷新页面,您将看到正确的缩放比例。 我使用以下CSS使我的图像具有响应性: 重要的是要注意,我有两张图片。视口为600px或以下时显示正方形图像。任何超过600px和全宽图像显示。这是控制在css与和。 我无法通过Br

  • 我对C#中的单例模式在C++中释放对象内存有一个困惑;这里是C++代码: 当我使用rocket::close()时,ms_rocket指向的内存空间将被释放,ms_rocket变成一个野指针,第二个“cout 在C#中,我认为当我使用Dispose()时,内存(B单例中的'a'对象)会被释放,但在第二次访问中,age值不应该是100,静态变量'a'会变得像野指针一样。谁能告诉我为什么?

  • 我在“独立Java SWING应用程序”中有下一个配置。我有一个问题:我的服务运行没有错误,执行DAO delete方法,但不提交delete: 坚持不懈xml Spring配置。xml 在我的项目的main()中,初始化spring上下文,并获取一个“服务”加载程序类: 我的SpringServiceLoader: 标记为@Transactional的我的serviceInterface的方法

  • 我使用Bulma作为我的CSS框架,在尝试使用它们的模态时,它们根本没有样式化,好像我遗漏了什么。 覆盖层就在那里,按钮似乎就位并且可见,但内容是灰色的。 我正在使用以下代码: Bulma的其他元素都在发挥作用。 注意:我不是在问JS部分,以及如何在Click上实际显示模态。我有纯粹的CSS问题。

  • 问题内容: 我以为Python交互模式下的显示总是等效的,但是事实并非如此。这是语言功能还是我缺少什么?谢谢 问题答案: 是的,此行为是故意的。 来自Python文档 7.1。表达陈述 Expression语句(通常是交互式地)用于计算和写入值,或(通常)用于调用过程(一个不返回有意义结果的函数;在Python中,过程返回value )。表达式语句的其他用法是允许的,有时是有用的。表达式语句的语法