eventloader.java

来自「hibernate quickly 一书的各章节源代码」· Java 代码 · 共 82 行

JAVA
82
字号
package com.manning.hq.ch04;



import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.Calendar;
import java.util.Date;

public class EventLoader {
    public static void main(String[] args) {
        Location1 location = new Location1();
        location.setName("Hilton Convention Center");
        location.setAddress("950 North Stafford St.");

        Event1 event = new Event1();
        event.setName("Annual Meeting");
        event.setDuration(60);
        event.setStartDate(createDate(2004, 11, 1));
        event.setLocation(location);

        Session session = null;
        Transaction tx = null;
        SessionFactory sessionFactory = null;
        try {
            Configuration configuration = new Configuration();
            // Configure from hibernate.cfg.xml at root of classpath.
            configuration.configure();
            sessionFactory = configuration.buildSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            session.save(event);
            session.save(location);

            session.flush();
            tx.commit();
            System.out.println("Event and location saved!");
        } catch (HibernateException e) {
            try {
                if(tx != null){
                    tx.rollback();
                }
            } catch (HibernateException ignore) {
                // ignore
            }
            throw e;
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (HibernateException ignore) {
                    // ignore
                }
            }
            if (sessionFactory != null) {
                try {
                    sessionFactory.close();
                } catch (HibernateException e) {
                    // ignore
                }
            }
        }
    }

    /**
     * @param year
     * @param month - This is 0 based 0 = January, 11 = December
     * @param day
     * @return
     */
    private static Date createDate(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?