第一个Hibernate应用程序

来源:互联网 发布:java http接口开发 编辑:程序博客网 时间:2024/04/30 11:45

hibernate版本 4.3

IDE eclipse 3.6 helios

1.JavaBean

public class Event {    private Long id;    private String title;    private Date date;    public Event() {}    public Long getId() {        return id;    }    private void setId(Long id) {        this.id = id;    }    public Date getDate() {        return date;    }    public void setDate(Date date) {        this.date = date;    }    public String getTitle() {        return title;    }    public void setTitle(String title) {        this.title = title;    }}
2.Configuration File

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="org.hibernate.tutorial.domain">    <class name="Event" table="EVENTS">        <id name="id" column="EVENT_ID">            <generator class="native"/>        </id>        <property name="date" type="timestamp" column="EVENT_DATE"/>        <property name="title"/>    </class></hibernate-mapping>

3.Hibernate Configuration

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <!-- 数据库连接设置 -->        <property name='connection.driver_class'>com.mysql.jdbc.Driver</property>        <property name='connection.url'>jdbc:mysql://localhost:3306/hibernate4.3</property>        <property name="connection.username">root</property>        <property name="connection.password">lee</property>       <!-- JDBC 连接池(使用内置的) -->        <property name="connection.pool_size">1</property>        <!-- SQL方言 -->        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>        <!--当前session线程安全  -->        <property name="current_session_context_class">thread</property>       <!-- 二级缓存无效 -->        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>        <!-- 回显所有执行的SQL至控制台 -->        <property name="show_sql">true</property>        <!--         1、update:表示自动根据model对象来更新表结构,启动hibernate时会自动检查数据库,如果缺少表,则自动建表;如果表里缺少列,则自动添加列。还有其他的参数: 2、create:启动hibernate时,自动删除原来的表,新建所有的表,所以每次启动后的以前数据都会丢失。3、create-drop:启动hibernate时,自动创建表,程序关闭时,自动把相应的表都删除。所以程序结束时,表和数据也不会再存在。         -->        <property name="hbm2ddl.auto">update</property><!-- Event对象映射文件,ORM意味对象关系映射,这个配置文件应该是定义Event对象和数据库对象的规则 -->        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>    </session-factory></hibernate-configuration>

4.工具类

public class HibernateUtil {    private static final SessionFactory sessionFactory = buildSessionFactory();    private static SessionFactory buildSessionFactory() {        try {            // Create the SessionFactory from hibernate.cfg.xml            return new Configuration().configure().buildSessionFactory();        }        catch (Throwable ex) {            // Make sure you log the exception, as it might be swallowed            System.err.println("Initial SessionFactory creation failed." + ex);            throw new ExceptionInInitializerError(ex);        }    }    public static SessionFactory getSessionFactory() {        return sessionFactory;    }}

5.测试CRUD

public class EventManager {    public static void main(String[] args) {        EventManager mgr = new EventManager();                if (args[0].equals("store")) {            mgr.createAndStoreEvent("My Event", new Date());        }        else if (args[0].equals("list")) {            List events = mgr.listEvents();            for (int i = 0; i < events.size(); i++) {                Event theEvent = (Event) events.get(i);                System.out.println(                        "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()                );            }        }        HibernateUtil.getSessionFactory().close();    }        /**     * insert a row     * @param title     * @param theDate     */    private void createAndStoreEvent(String title, Date theDate) {    //获取当前Session        Session session = HibernateUtil.getSessionFactory().getCurrentSession();        //开启事务        session.beginTransaction();        Event theEvent = new Event();        theEvent.setTitle(title);        theEvent.setDate(theDate);        session.save(theEvent);                //提交事务        session.getTransaction().commit();    }        /**     * query rows     * @return     */    private List listEvents() {        Session session = HibernateUtil.getSessionFactory().getCurrentSession();        session.beginTransaction();        List result = session.createQuery("from Event").list();        session.getTransaction().commit();        return result;    }}

在线manu:http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/

0 0
原创粉丝点击