1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.mapping;
17
18 import java.sql.Connection;
19 import java.sql.SQLException;
20 import java.util.Properties;
21
22 import javax.sql.DataSource;
23
24 import org.apache.ibatis.builder.BuilderException;
25
26
27
28
29
30
31
32
33
34
35 public class VendorDatabaseIdProvider implements DatabaseIdProvider {
36
37 private Properties properties;
38
39 @Override
40 public String getDatabaseId(DataSource dataSource) {
41 if (dataSource == null) {
42 throw new NullPointerException("dataSource cannot be null");
43 }
44 try {
45 return getDatabaseName(dataSource);
46 } catch (SQLException e) {
47 throw new BuilderException("Error occurred when getting DB product name.", e);
48 }
49 }
50
51 @Override
52 public void setProperties(Properties p) {
53 this.properties = p;
54 }
55
56 private String getDatabaseName(DataSource dataSource) throws SQLException {
57 String productName = getDatabaseProductName(dataSource);
58 if (properties == null || properties.isEmpty()) {
59 return productName;
60 }
61 return properties.entrySet().stream().filter(entry -> productName.contains((String) entry.getKey()))
62 .map(entry -> (String) entry.getValue()).findFirst().orElse(null);
63 }
64
65 private String getDatabaseProductName(DataSource dataSource) throws SQLException {
66 try (Connection con = dataSource.getConnection()) {
67 return con.getMetaData().getDatabaseProductName();
68 }
69 }
70
71 }