Hibernate測試和Util

package com.cc.test;

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

import com.cc.model.Student;

public class StudentTest {

	public static void main(String[] args) {
		Student s = new Student();
		s.setId(2);
		s.setName("s");
		s.setAge(1);
		
		
		Configuration cfg = new Configuration();
		SessionFactory sf = cfg.configure().buildSessionFactory();
		Session session = sf.openSession();//一般用getCurrentSession()
 		session.beginTransaction();
		
		session.save(s);
		session.getTransaction().commit();
		
		session.close();
		sf.close();
	}
}


  Hinernate 的 Utils

package com.cc.util;

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

public class HibernateUtil {

	private static SessionFactory sessionFactory;

	private HibernateUtil() {
	}

	// 初始化
	static {
		Configuration cfg = new Configuration();
		cfg.configure();
		sessionFactory = cfg.buildSessionFactory();
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Session getSession() {
		return sessionFactory.openSession();
	}

}


發佈了40 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章