1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.generator.internal;
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.api.ConnectionFactory;
27 import org.mybatis.generator.config.JDBCConnectionConfiguration;
28
29
30
31
32
33
34
35
36
37 public class JDBCConnectionFactory implements ConnectionFactory {
38
39 private String userId;
40 private String password;
41 private String connectionURL;
42 private String driverClass;
43 private Properties otherProperties;
44
45
46
47
48
49
50
51
52 public JDBCConnectionFactory(JDBCConnectionConfiguration config) {
53 super();
54 userId = config.getUserId();
55 password = config.getPassword();
56 connectionURL = config.getConnectionURL();
57 driverClass = config.getDriverClass();
58 otherProperties = config.getProperties();
59 }
60
61
62
63
64
65 public JDBCConnectionFactory() {
66 super();
67 }
68
69 @Override
70 public Connection getConnection() throws SQLException {
71
72 Properties props = new Properties();
73
74 if (stringHasValue(userId)) {
75 props.setProperty("user", userId);
76 }
77
78 if (stringHasValue(password)) {
79 props.setProperty("password", password);
80 }
81
82 props.putAll(otherProperties);
83
84 Driver driver = getDriver();
85 Connection conn = driver.connect(connectionURL, props);
86
87 if (conn == null) {
88 throw new SQLException(getString("RuntimeError.7"));
89 }
90
91 return conn;
92 }
93
94 private Driver getDriver() {
95 Driver driver;
96
97 try {
98 Class<?> clazz = ObjectFactory.externalClassForName(driverClass);
99 driver = (Driver) clazz.getConstructor().newInstance();
100 } catch (Exception e) {
101 throw new RuntimeException(getString("RuntimeError.8"), e);
102 }
103
104 return driver;
105 }
106
107 @Override
108 public void addConfigurationProperties(Properties properties) {
109
110
111 userId = properties.getProperty("userId");
112 password = properties.getProperty("password");
113 connectionURL = properties.getProperty("connectionURL");
114 driverClass = properties.getProperty("driverClass");
115
116 otherProperties = new Properties();
117 otherProperties.putAll(properties);
118
119
120 otherProperties.remove("userId");
121 otherProperties.remove("password");
122 otherProperties.remove("connectionURL");
123 otherProperties.remove("driverClass");
124 }
125 }