1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.generator.internal.db;
17
18 import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
19 import static org.mybatis.generator.internal.util.messages.Messages.getString;
20
21 import java.sql.Connection;
22 import java.sql.Driver;
23 import java.sql.SQLException;
24 import java.util.Properties;
25
26 import org.mybatis.generator.config.JDBCConnectionConfiguration;
27 import org.mybatis.generator.internal.ObjectFactory;
28
29
30
31
32
33
34
35
36
37 public class ConnectionFactory {
38
39 private static ConnectionFactory instance = new ConnectionFactory();
40
41 public static ConnectionFactory getInstance() {
42 return instance;
43 }
44
45
46
47
48 private ConnectionFactory() {
49 super();
50 }
51
52 public Connection getConnection(JDBCConnectionConfiguration config)
53 throws SQLException {
54 Driver driver = getDriver(config);
55
56 Properties props = new Properties();
57
58 if (stringHasValue(config.getUserId())) {
59 props.setProperty("user", config.getUserId());
60 }
61
62 if (stringHasValue(config.getPassword())) {
63 props.setProperty("password", config.getPassword());
64 }
65
66 props.putAll(config.getProperties());
67
68 Connection conn = driver.connect(config.getConnectionURL(), props);
69
70 if (conn == null) {
71 throw new SQLException(getString("RuntimeError.7"));
72 }
73
74 return conn;
75 }
76
77 private Driver getDriver(JDBCConnectionConfiguration connectionInformation) {
78 String driverClass = connectionInformation.getDriverClass();
79 Driver driver;
80
81 try {
82 Class<?> clazz = ObjectFactory.externalClassForName(driverClass);
83 driver = (Driver) clazz.newInstance();
84 } catch (Exception e) {
85 throw new RuntimeException(getString("RuntimeError.8"), e);
86 }
87
88 return driver;
89 }
90 }