import net.sf.hibernate.*; import net.sf.hibernate.cfg.Configuration; import net.sf.hibernate.cfg.Environment; import javax.swing.*; import java.util.List; import java.util.Iterator; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; /** * User: aps Date: 23-Jan-2005 Time: 15:18:00 */ public class Main { private static final Log LOG = LogFactory.getLog(Main.class); private static SessionFactory sessions = null; public static void main(String[] args) { boolean createDb = false; if (args.length == 1 && "create".equals(args[0].toLowerCase())) createDb = true; else if (args.length != 0) { System.err.println("Usage: java Main [create]"); System.exit(1) ; } Configuration cfg = new Configuration(); try { cfg.addClass(Message.class); String username = cfg.getProperty("hibernate.connection.username"); // get the username and password via a Swing JDialog box String[] userNamePassword = getUsernamePassword(username); if (userNamePassword != null) { cfg.setProperty("hibernate.connection.username", userNamePassword[0]); cfg.setProperty("hibernate.connection.password", userNamePassword[1]); } if (createDb) { LOG.info("(Re-)creating the database: old data will be destroyed"); cfg.setProperty(Environment.HBM2DDL_AUTO, "create"); } LOG.trace("Building the Session Factory"); sessions = cfg.buildSessionFactory(); LOG.trace("About to add message"); String msgText = "Hello World"; Long id = null; id = addMessage(msgText); LOG.trace("Added Message"); LOG.trace("Message saved to database"); printMessages(); String[] msgs = {"Take me to your leader...", "...(please)"}; updateMessage(id, "Greetings Earthling", msgs); LOG.trace("Message Updated"); printMessages(); } catch (Exception e) { e.printStackTrace(); } System.exit(0); } private static Long addMessage(String msgText) throws HibernateException { Session session = sessions.openSession(); Transaction tx = null; Message message = null ; try { tx = session.beginTransaction(); message = new Message(msgText); // At this point, Message is "Transient" session.save(message); // Now it is "Persistent" tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); throw e; } finally { session.close(); } // Note that the following works even though message is no longer associated with a session, // i.e., it is "Detached": return message.getId(); } private static void printMessages() throws HibernateException { Session session = sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); List messages = session.find("from Message as m order by m.id asc"); System.out.println("Number of messages found: " + messages.size()); for (Iterator iter = messages.iterator() ; iter.hasNext() ;) { Message m = (Message) iter.next(); System.out.println(m.getId() + ": " + m.getText()); } tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); throw e; } finally { session.close(); } } private static void updateMessage(Long msgID, String msgText, String[] msgTexts) throws HibernateException { Session session = sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Message message = (Message) session.load(Message.class, msgID); message.setText(msgText); for (int i = 0 ; i < msgTexts.length ; i++) { Message nextMessage = new Message(msgTexts[i]); message.setNextMessage(nextMessage); message = nextMessage; } tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); throw e; } finally { session.close(); } } /** * Shows a dialog box for the user to enter a password and a username. Note that using this * method means that the application must be terminated by calling System.exit(0) * to ensure that all the Swing threads created by this method are terminated and the JVM * can exit. * * @param initialUsername the String that the username field in the dialog * should be initialised to. * @return null if the user clicked on the CANCEL button or on * the window close button. Otherwise an array of 2 Strings is returned. * The first String in the array is the username entered, the second * is the password. */ private static String[] getUsernamePassword(String initialUsername) { JTextField username = new JTextField((initialUsername == null) ? "" : initialUsername, 20); JPasswordField password = new JPasswordField(20); final Object[] fields = {"Enter your database password:", password, "Enter your database username:", username}; JOptionPane pane = new JOptionPane(fields, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null); JDialog d = pane.createDialog(null, "Database Access"); d.setVisible(true); Integer returnValue = (Integer) pane.getValue(); d.dispose(); if (returnValue == null || returnValue.intValue() != JOptionPane.OK_OPTION) return null; String[] ret = {username.getText(), new String(password.getPassword())}; return ret; } }