1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| package com.hello;
import org.hibernate.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
// ############################################################################
// First unit of work
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message("Hello World");
session.save(message);
tx.commit();
session.close();
// ############################################################################
// Second unit of work
Session secondSession = HibernateUtil.getSessionFactory().openSession();
Transaction secondTransaction = secondSession.beginTransaction();
List messages =
secondSession.createQuery("from Message m order by m.text asc").list();
System.out.println( messages.size() + " message(s) found:" );
for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
Message loadedMsg = (Message) iter.next();
System.out.println( loadedMsg.getText() );
}
secondTransaction.commit();
secondSession.close();
// ############################################################################
// Third unit of work
Session thirdSession = HibernateUtil.getSessionFactory().openSession();
Transaction thirdTransaction = thirdSession.beginTransaction();
// message.getId() holds the identifier value of the first message
Message loadedMessage = (Message) thirdSession.get( Message.class, message.getId());
loadedMessage.setText( "Greetings Earthling" );
loadedMessage.setNextMessage(
new Message( "Take me to your leader (please)" )
);
thirdTransaction.commit();
thirdSession.close();
// ############################################################################
// Final unit of work (just repeat the query)
// TODO: You can move this query into the thirdSession before the commit, makes more sense!
Session fourthSession = HibernateUtil.getSessionFactory().openSession();
Transaction fourthTransaction = fourthSession.beginTransaction();
messages =
fourthSession.createQuery("from Message m order by m.text asc").list();
System.out.println( messages.size() + " message(s) found:" );
for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
Message loadedMsg = (Message) iter.next();
System.out.println( loadedMsg.getText() );
}
fourthTransaction.commit();
fourthSession.close();
// Shutting down the application
HibernateUtil.shutdown();
}
} |
Partager