?
?1
import
?org.apache.commons.logging.Log;
?2
import
?org.apache.commons.logging.LogFactory;
?3
import
?org.hibernate.FlushMode;
?4
import
?org.hibernate.HibernateException;
?5
import
?org.hibernate.Session;
?6
import
?org.hibernate.SessionFactory;
?7
import
?org.hibernate.Transaction;
?8
import
?org.hibernate.cfg.Configuration;
?9
10
11
12
public
?
class
?SessionManager?
{
13
????
private
?
static
?Log?log?
=
?LogFactory.getLog(SessionManager.
class
);
14
????
private
?
static
?
final
?SessionFactory?sessionFactory;
15
????
/**?*/
/**
靜態塊:創建session?factory
*/
16
????
static
?
{
17
????????
try
?
{
18
????????????System.out.println(
"
數據映射初始化
begin
"
);
19
????????????Configuration?configure?
=
?
new
?Configuration().configure();
20
????????????sessionFactory?
=
configure.buildSessionFactory();
21
????????????
/**/
/*
URL?configFileURL?=
22
????????????????????SessionManager.class.getResource("/hibernate.cfg.xml");
23
????????????Configuration?configure?=?(new?Configuration()).configure(configFileURL);
*/
24
????????????System.out.println(
"
數據映射初始化
end
"
);
25
????????}
?
catch
?(Throwable?ex)?
{
26
????????????log.error(
"
Initial?SessionFactory?creation?failed.
"
,?ex);
27
????????????
throw
?
new
?ExceptionInInitializerError(ex);
28
????????}
29
????}
30
????
/**?*/
/**
獲取當前線程的session對象
*/
31
????
public
?
static
?Session?currentSession()?
throws
?HibernateException?
{
32
????????Session?s?
=
?sessionFactory.openSession();
33
????????s.setFlushMode(FlushMode.NEVER);
34
????????
return
?s;
35
????}
36
????
public
?
static
?Session?currentSessionFlush()?
throws
?HibernateException?
{
37
????????Session?s?
=
?sessionFactory.openSession();
38
????????s.setFlushMode(FlushMode.AUTO);
39
????????
return
?s;
40
????}
41
????
/**?*/
/**
關閉當前線程所在的session對象
*/
42
????
public
?
static
?
void
?closeSession(Session?s)?
throws
?HibernateException?
{
43
????????
if
?(s?
!=
?
null
)
{
44
????????????s.close();
45
????????}
46
????}
47
????
public
?
static
?SessionFactory?getSessionFactory()?
{
48
????????
if
(sessionFactory
!=
null
)
{
49
????????????
return
?sessionFactory;
50
????????}
51
????????
else
{
52
????????????System.out.println(
"
無效的factiory
"
);
53
????????????
return
?
null
;
54
????????}
55
????}
56
}
57

?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
