first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

Hibernate in Action Notes: Chapter 2; Introducing and integrating Hibernate; 2.1 “Hello World” with Hibernate

2.1 “Hello World” with Hibernate

"Hibernate applications define persistent classes that are 'mapped' to database tables... Our persistent class can be used in any execution context at all---no special container is needed." Hibernate depends on its Session object for its "context":

Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message("Hello World");
session.save(message);
tx.commit();
session.close();

The Message is defined by:

package hello;
public class Message
{
    /*
        There is no need to set the id property explicitly.
        The XML configuration file associates
        the <generator /> element
        with this "identifier property".
    */
    private Long id;

    /*
        The XML configuration file "maps" the private text
        member to the MESSAGE_TEXT column in the database
        with the <property /> element.
    */
    private String text;

    /*
        this reference to another Message object is used by
        the XML configuration in the <many-to-one /> element.
    */
    private Message nextMessage;

    //Hibernate requires this private constructor:
    private Message() {}

    public Message(String text) { this.text = text; }

    public Long getId() { return id; }

    /*
        Note that setId() is private because
        of Hibernate (see private id above):
    */
    private void setId(Long id) { this.id = id; }

    public String getText() { return this.text; }
    public void setText(String text) { this.text = text; }

    /*
        The members below are useful because of Hibernate,
        its "cascading save" feature.
    */
    public Message getNextMessage() { return this.nextMessage; }
    public void setNextMessage(Message this.nextMessage)
    {
        this.nextMessage = nextMessage;
    }
}

Hibernate recognizes the Message class because of this XML configuration file or "XML mapping document":

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
<class name="hello.Message" table="MESSAGES">

<id name="id" column="MESSAGE_ID">
    <generator class="increment"/>
</id>

<property name="text" column="MESSAGE_TEXT"/>

<many-to-one
    name="nextMessage"
    cascade="all"
    column="NEXT_MESSAGE_ID"/>

</class>
</hibernate-mapping>
mod date: 2007-04-10T01:38:56.000Z