Question

i've created the Hibernate project using Spring Template Project. Two domain objects, a JUnit test, app-context.xml and the persistence-context.xml were created. Now i noticed this line

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

and assume that the following happens

  1. A default HQSL db is used
  2. The two created models Order.java & Item.java will automatically created in memory tables T_ORDER and T_ITEM and the these will be mapped as per annotations on the objects. Inside the auto created classes one of the test methods is as follows

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

Questions ...

  1. Am i correct to think that the in memory tables are created from the domain models (Order/Item), and mapped? Therefore session.flush() synchronize the object to the physical (in memory table)....
  2. Are these tables auto mapped because if i do the following

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

i get an exception...

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

if these tables are not mapped automatically, how is flushing working at the first place?

Was it helpful?

Solution

Table creation is a feature of Hibernate (and other JPA proviers). It taking place when the application/test starts. It has nothing to do with any query. Even if you only start your test, with Hibernate running and configured, it can create the tables.

If Hibernate create the tables, drop old once, and so on, depends on its configuration: the property: hibernate.hbm2ddl.auto is used what hibernate do if its starts. For example the value update will add not existing tables and columns.

More details can be found in the documentation.

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top