CHAPTER 2 Starting a (Web hosting solutions) project The first unit
CHAPTER 2 Starting a project The first unit of work, if run, results in the execution of something similar to the following SQL: insert into MESSAGES (MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID) values (1, ‘Hello World’, null) Hold on the MESSAGE_ID column is being initialized to a strange value. You didn t set the id property of message anywhere, so you expect it to be NULL, right? Actually, the id property is special. It s an identifier property: It holds a generated unique value. The value is assigned to the Message instance by Hibernate when save() is called. (We ll discuss how the value is generated later.) Look at the second unit of work. The literal string “from Message m order by m.text asc” is a Hibernate query, expressed in HQL. This query is internally translated into the following SQL when list() is called: select m.MESSAGE_ID, m.MESSAGE_TEXT, m.NEXT_MESSAGE_ID from MESSAGES m order by m.MESSAGE_TEXT asc If you run this main() method (don t try this now you still need to configure Hibernate), the output on your console is as follows: 1 message(s) found: Hello World If you ve never used an ORM tool like Hibernate before, you probably expected to see the SQL statements somewhere in the code or mapping metadata, but they aren t there. All SQL is generated at runtime (actually, at startup for all reusable SQL statements). Your next step would normally be configuring Hibernate. However, if you feel confident, you can add two other Hibernate features automatic dirty checking and cascading in a third unit of work by adding the following code to your main application: // Third unit of work Session thirdSession = HibernateUtil.getSessionFactory().openSession(); Transaction thirdTransaction = thirdSession.beginTransaction(); // msgId holds the identifier value of the first message message = (Message) thirdSession.get( Message.class, msgId ); message.setText( “Greetings Earthling” ); message.setNextMessage( new Message( “Take me to your leader (please)” ) ); thirdTransaction.commit(); thirdSession.close();
Check Tomcat Web Hosting services for best quality webspace to host your web application.