⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 eventloader.java

📁 hibernate quickly 一书的各章节源代码
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -