1

我已经使用 Spring Template Project 创建了 Hibernate 项目。创建了两个域对象,一个 JUnit 测试 app-context.xml 和 persistence-context.xml。现在我注意到了这条线

<jdbc:embedded-database id="dataSource"></jdbc:embedded-database>

并假设发生以下情况

  1. 使用默认 HQSL 数据库
  2. 两个创建的模型 Order.java 和 Item.java 将在内存表 T_ORDER 和 T_ITEM 中自动创建,并且这些模型将根据对象上的注释进行映射。在自动创建的类中,其中一种测试方法如下

    @Test
    @Transactional
    public void testSaveAndGet() throws Exception {
        Session session = sessionFactory.getCurrentSession();
        Order order = new Order();
        order.getItems().add(new Item());
        session.save(order);
        session.flush();
        // Otherwise the query returns the existing order
        // (and we didn't set the parent in the item)...
        session.clear();
        Order other = (Order) session.get(Order.class, order.getId());
        assertEquals(1, other.getItems().size());
        assertEquals(other, other.getItems().iterator().next().getOrder());
    }
    

问题 ...

  1. 我是否认为内存表是从域模型(订单/项目)创建并映射的?因此 session.flush() 将对象同步到物理(在内存表中)......
  2. 这些表是否自动映射,因为如果我执行以下操作

    session.save(order);
    session.flush();
    session.clear();
    Order other = (Order) session
       .createQuery("from T_ORDER where ORDER_ID =: orderid")
       .setLong("orderid", order.getId())
       .uniqueResult();
    

我有一个例外...

org.hibernate.hql.ast.[B]QuerySyntaxException[/B]: \
T_ORDER is not mapped [from T_ORDER where ORDER_ID =: orderid]
............
............

如果这些表没有自动映射,那么刷新首先是如何工作的?

4

1 回答 1

1

表创建是 Hibernate(和其他 JPA 提供者)的一个特性。它发生在应用程序/测试开始时。它与任何查询无关。即使您只是开始测试,在 Hibernate 运行和配置的情况下,它也可以创建表。

如果 Hibernate 创建表、删除旧表等等,取决于它的配置:属性:hibernate.hbm2ddl.auto使用 hibernate 在启动时执行的操作。例如,该值update将添加不存在的表和列。

更多细节可以在文档中找到。

Your Exception When you uses Hibernate and write hibernate query statements, then you have to use HQL and not SQL. -- The main difference is that HQL is based on the classes but not on the tables. So in your case you must not use T_ORDER, but Order (the same is for the id, you need to use the property/field name, but not the column name).

于 2011-01-19T09:37:46.027 回答