Friday, 16 May 2008

Hibernate - The Basics (Part 1)

Have been working on a new project recently, finally get to really deal with the basics of Hibernate. Here are two basic things that I've learnt so far:
  1. The concept of "Persistent":
    My intention is to insert two new rows into a database table.
    Bean bean = new Bean("Hello");
    session.save(bean);

    bean.setName("Bye");
    session.save(bean);
    But this isn't going to work!!! With the first save action, it has already 'persisted' the bean. Hibernate remembers that you have already saved the bean, so with the second save action, it will think that you are trying to save the same bean and rather than something new that represents a new row.

    So in order to insert a second row into the table, I MUST create a new instance of Bean before I try calling the save action again.

  2. The concept of "Dirty" data:
    Let's say I have already persisted a bean. I then update the bean and try to get the same type of bean from the database.
    Bean bean = new Bean("Hello");
    session.save(bean);

    bean.setName("Hi"); // updated the bean with new value
    Bean retrievedBean = getBeanFromDB(bean.getName());
    You would've think the "get" method will only execute a SELECT query. But WRONG! Hibernate is smart enough to realise that the bean that it persisted is dirty (i.e. its data has been updated). In the "get" method, Hibernate goes "ah oh...need to retrieve some Bean objects from the table. I know some data is dirty, I must write it to the DB first, so I can return the latest data back to the user".

1 comment:

  1. Well once upon a time when I first started, I was one of the first people in the company to learn Hibernate, and I share the same sentiment as this forum poster....(who isn't me of course!)

    http://forums.hibernate.org/viewtopic.php?t=969583&highlight=bourbon&sid=c1f96a7db2552a2ba74a7e32f4f6b1b8

    ReplyDelete