1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| package com.zhanghe.study;
import com.zhanghe.study.model.User; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry;
public class Main { private static final SessionFactory sessionFactory; static { try { Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } }
public static Session getSession() throws HibernateException { return sessionFactory.openSession(); }
public static void main(final String[] args) throws Exception { final Session session = getSession(); Transaction transaction = session.beginTransaction(); try { User user = new User(); user.setAge(20); user.setName("张三"); session.save(user); transaction.commit(); } catch (Exception e){ transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } }
|