A simple Hibernate sample

Some days ago. I bought a book named Java Persistence with Hibernate.

Now , I will show a simple sample for everybody who wanna learn the skill of Hibernate.

 

Step one.

      Create a class named Message,Of course ,you should have created a project in IDE.

 

Message.java
package hello;

public class Message {
    private Long id;
    private String text;
    private Message nextMessage;
    Message()
    {

    }
    public Message(String text)
    {
        this.text = text;
    }
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Message getNextMessage() {
        return nextMessage;
    }

    public void setNextMessage(Message nextMessage) {
        this.nextMessage = nextMessage;
    }

    public String getText() {
        return text;
    }

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

 

}


Step two.

   create a XML named Message.hbm.xml.Just like the following.

 

Message.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.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" foreign-key="FK_NEXT_MESSAGE"/>
    </class>
 </hibernate-mapping>

 

Step three.

Write you property file.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@126.1.1.63:1521:oradb</property>
    <property name="hibernate.connection.username">timesheet</property>
    <property name="hibernate.connection.password">timesheet</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.use_sql_comments">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <mapping  resource="hello/Message.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

 

Step four

 

Configurating you DataBase,and run the main method like this

Oh.I forgot that ,before you run this project ,you'd better create a manage bena for Hibernate.

I write a class named HibernateUtil.

 

HibernateUtil.java

package persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    static
    {
        try
        {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }
        catch(Throwable ex)
        {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
    public static void shutdown()
    {
        getSessionFactory().close();
    }
}

then you should have the Main Class lik this.


package hello;

import org.hibernate.*;
import java.util.*;
import persistence.*;

/**
 *
 * @author zhangqi
 */
public class HelloWorld {

    public static void main(String[] args)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        Message message = new Message("Hello World2");
        Long msgId =(Long)session.save(message);
        System.out.println(msgId);
        tx.commit();;
        session.close();


        Session newSession = HibernateUtil.getSessionFactory().openSession();
        Transaction newTx = newSession.beginTransaction();
        List messages = newSession.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.getId() +" "+loadedMsg.getText());
        }
        newTx.commit();;
        newSession.close();
        HibernateUtil.shutdown();

    }
}
Yeah.run it ,you will get the answer

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章