1
|
package eu.dnetlib.utils.hibernate;
|
2
|
|
3
|
import org.apache.log4j.Logger;
|
4
|
import org.hibernate.Session;
|
5
|
import org.hibernate.SessionFactory;
|
6
|
import org.hibernate.cfg.AnnotationConfiguration;
|
7
|
import org.hibernate.cfg.Configuration;
|
8
|
|
9
|
public class HibernateUtil {
|
10
|
private String host;
|
11
|
private String catalog;
|
12
|
private String username;
|
13
|
private String password;
|
14
|
private SessionFactory sessionFactory;
|
15
|
private Logger logger = Logger.getLogger(this.getClass());
|
16
|
|
17
|
public HibernateUtil() {
|
18
|
}
|
19
|
|
20
|
public HibernateUtil(String host, String catalog, String username,
|
21
|
String password) {
|
22
|
super();
|
23
|
this.host = host;
|
24
|
this.catalog = catalog;
|
25
|
this.username = username;
|
26
|
this.password = password;
|
27
|
}
|
28
|
|
29
|
public void setHost(String host) {
|
30
|
this.host = host;
|
31
|
}
|
32
|
|
33
|
public void setCatalog(String catalog) {
|
34
|
this.catalog = catalog;
|
35
|
}
|
36
|
|
37
|
public void setUsername(String username) {
|
38
|
this.username = username;
|
39
|
}
|
40
|
|
41
|
public void setPassword(String password) {
|
42
|
this.password = password;
|
43
|
}
|
44
|
|
45
|
public Session getSession() {
|
46
|
if ((sessionFactory == null) || sessionFactory.isClosed())
|
47
|
this.configure();
|
48
|
|
49
|
return sessionFactory.getCurrentSession();
|
50
|
}
|
51
|
|
52
|
private void configure() {
|
53
|
Configuration configuration = new AnnotationConfiguration().configure();
|
54
|
String url = "jdbc:mysql://" + host + "/" + catalog
|
55
|
+ "?characterEncoding=UTF-8";
|
56
|
configuration.setProperty("hibernate.connection.url", url);
|
57
|
configuration.setProperty("hibernate.connection.username", username);
|
58
|
configuration.setProperty("hibernate.connection.password", password);
|
59
|
|
60
|
if (logger.isDebugEnabled())
|
61
|
logger.debug("Connecting to url " + url + ", username: " + username
|
62
|
+ ", password: " + password);
|
63
|
|
64
|
this.sessionFactory = configuration.buildSessionFactory();
|
65
|
}
|
66
|
|
67
|
public SessionFactory getSessionFactory() {
|
68
|
if ((sessionFactory == null) || sessionFactory.isClosed())
|
69
|
this.configure();
|
70
|
|
71
|
return sessionFactory;
|
72
|
}
|
73
|
|
74
|
public void setSessionFactory(SessionFactory sessionFactory) {
|
75
|
this.sessionFactory = sessionFactory;
|
76
|
}
|
77
|
}
|