1 package ru.indvdum.jpa.init;
3 import java.util.ResourceBundle;
5 import javax.naming.InitialContext;
6 import javax.naming.NamingException;
8 import org.apache.commons.dbcp.BasicDataSource;
10 import ru.indvdum.jpa.dao.JPAPropertySelector;
11 import ru.indvdum.jpa.props.Props;
14 * @author indvdum (gotoindvdum[at]gmail[dot]com)
15 * @since 10.11.2012 21:40:11
18 public class DatabaseInitializer {
20 protected static String dataSource = null;
22 protected static String getDataSourceName() {
23 if (dataSource != null)
26 if (dataSource == null)
27 dataSource = System.getProperty(Props.DATA_SOURCE_PROPERTY);
28 if (dataSource == null)
29 dataSource = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.DATA_SOURCE_PROPERTY);
30 if (dataSource == null)
31 dataSource = "jdbc/database";
35 public static void init() throws NamingException {
36 String url = System.getProperty(Props.DATABASE_URL_PROPERTY);
37 String driver = System.getProperty(Props.DATABASE_DRIVER_PROPERTY);
38 String username = System.getProperty(Props.DATABASE_USERNAME_PROPERTY);
39 String password = System.getProperty(Props.DATABASE_PASSWORD_PROPERTY);
40 String maxActive = System.getProperty(Props.DATABASE_MAX_ACTIVE_PROPERTY);
42 BasicDataSource dataSource = new BasicDataSource();
43 dataSource.setUrl(url);
44 dataSource.setDriverClassName(driver);
45 dataSource.setUsername(username);
46 dataSource.setPassword(password);
47 if (maxActive != null && maxActive.matches("\\d+"))
48 dataSource.setMaxActive(Integer.parseInt(maxActive));
55 public static void init(BasicDataSource dataSource) throws NamingException {
56 InitialContext context = new InitialContext();
57 BasicDataSource existedDataSource = (BasicDataSource) context.lookup(getDataSourceName());
58 if (existedDataSource == null)
59 context.bind(getDataSourceName(), dataSource);
62 public static void initDerby() throws NamingException {
63 System.setProperty("derby.stream.error.field", "java.lang.System.err");
65 BasicDataSource dataSource = new BasicDataSource();
66 dataSource.setUrl("jdbc:derby:memory:myDb;create=true");
67 dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
68 dataSource.setUsername("");
69 dataSource.setPassword("");
70 dataSource.setMaxActive(2);
74 JPAPropertySelector.setSystemProperty(JPAPropertySelector.RUNTIMEENHANCEMENT, "supported");
75 JPAPropertySelector.setSystemProperty(JPAPropertySelector.SHOWSQL, "true");
76 JPAPropertySelector.setSystemProperty(JPAPropertySelector.SYNCHRONIZEDB, "true");