03_传智播客hibernate教程

aquahellishSoftware and s/w Development

Dec 13, 2013 (3 years and 6 months ago)

61 views

03_
传智播客
桩b敲湡瑥
教程
_桩扥b湡ne
入门案例的代码优化

package org.sicn.lee.test;


import java.util.Date;


import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import org.junit.BeforeClass;

import org.junit.Test;

import

org.sicn.lee.domain.User;


public class BaseTest {



@BeforeClass


public static void setUpBeforeClass() throws Exception {


}



@Test


public void test() {



Configuration cfg=new Configuration();



cfg.configure();



SessionFactory factory=cfg.buildSess
ionFactory();



Session session=factory.openSession();



session.getTransaction().begin();



User user=new User();



user.setBirthday(new Date());



user.setName("name");



session.save(user);



session.beginTransaction().commit();



session.close();



fac
tory.close();



System.out.println("end");


}

}

红色的部分重复做是非常耗时的。


使用一个工具类
:

package

org.sicn.lee.test;


import

org.hibernate.SessionFactory;

import

org.hibernate.cfg.Configuration;


public

final

class

HibernateUtil {


private

static

final

SessionFactory
se
ssionFactory

=
buildSessionFactory
();



private

static

SessionFactory buildSessionFactory() {



try

{




return

new

Configuration().configure().buildSessionFactory();



}
catch

(Throwable ex) {




System.
err
.println(
"Initial SessionFactory creation failed.
"

+
ex);




throw

new

ExceptionInInitializerError(ex);



}


}



public

static

SessionFactory getSessionFactory() {



return

sessionFactory
;


}

}


导入辅助类之后的实例化


package org.sicn.lee.test;


import java.util.Date;


import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import org.junit.BeforeClass;

import org.junit.Test;

import org.sicn.lee.domain.User
;


public class BaseTest {



@BeforeClass


public static void setUpBeforeClass() throws Exception {


}



@Test


public void test() {



SessionFactory factory=HibernateUtil.getSessionFactory();



Session session=factory.openSession();



session.getTransacti
on().begin();



User user=new User();



user.setBirthday(new Date());



user.setName("name");



session.save(user);



session.beginTransaction().commit();



session.close();



factory.close();



System.out.println("end");


}

}