将数据库类型映射到具体的 Java 类
背景
将列数据类型映射到其相应的 Java 类。
问题
查询从数据库返回元信息:
SELECT
rb.object_schema,
rb.object_name,
rb.column_name
FROM
dictionary.resource_bundle rb
例如,此查询返回(自引用):
dictionary, resource_bundle, column_name
其中“dictionary”是架构名称,“resource_bundle”是object_name,“column_name”是column_name。
最好执行以下操作:
SELECT
rb.object_schema,
rb.object_name,
rb.column_name,
rb.column_type
FROM
dictionary.resource_bundle rb
并让此查询返回:
dictionary, resource_bundle, column_name, varchar
然后使用 JDBC 发现 varchar
是 映射到java.lang.String
。
问题
- 在 PostgreSQL 中,给定模式名称、对象名称(保证是表或视图)和列名称,如何确定使用什么类型来存储数据?
- 以与数据库无关的方式(利用 JDBC),如何确定数据库用于给定数据类型的映射?
Background
Map a column data type to its corresponding Java class.
Problem
A query returns meta information from a database:
SELECT
rb.object_schema,
rb.object_name,
rb.column_name
FROM
dictionary.resource_bundle rb
For example, this query returns (the self-referential):
dictionary, resource_bundle, column_name
Where 'dictionary' is the schema name, 'resource_bundle' is the object_name, and 'column_name' is the column_name.
It would be great to do something like:
SELECT
rb.object_schema,
rb.object_name,
rb.column_name,
rb.column_type
FROM
dictionary.resource_bundle rb
And have this query return:
dictionary, resource_bundle, column_name, varchar
Then use JDBC to discover that varchar
is mapped to java.lang.String
.
Questions
- In PostgreSQL, how do you determine what type is used to store the data, given a schema name, object name (guaranteed to be table or view), and column name?
- In a database-neutral fashion (leveraging JDBC), how do you determine the mapping a database uses for a given data type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方案
答案比使用
getMetaData
方法更复杂,因为getMetaData
方法返回的整数类型和完整类名没有直接映射。该解决方案需要两段代码:Java 类型方法
以下方法检索元信息:
静态转换方法
常量整数值必须转换为类名。这可以按如下方式完成:
请注意,不同的数据库在映射上可以有不同的变体。
Solution
The answer is more complicated than using the
getMetaData
method because there is no direct mapping from the integer types returned by thegetMetaData
method and the full class name. This solution requires two pieces of code:java.sql.Types
constant integer value.Java Type Method
The following method retrieves the meta information:
Static Conversion Method
The constant integer values must be translated to a class name. This can be accomplished as follows:
Note that different databases can have different variations on the mapping.
JDBC 提供了内省数据库元信息的方法。
从 JDBC 连接,调用 getMetaData 和 getColumns 从那里向下钻取以获取模式信息,表和列。
JDBC provides the means to introspect database meta information.
From a JDBC Connection, call getMetaData and getColumns drill down from there to get information for schemas, tables and, columns.