postgresql 如何将标准 Java 类型映射到 SQL 类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5008348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-20 00:33:33  来源:igfitidea点击:

How to map standard Java types to SQL types?

javapostgresqljdbctypesrelational-database

提问by user573215

I want to write a program, which creates RDBMS-tables through JDBC automatically. To add columns to a table, I need to know the name of the column and the column's RDBMS datatype. I already have the names of the columns. I don't have the RDBMS types for the columns, but I have Java types for those column. So I need to map those Java types to RDBMS datatypes. The Java type can be one of the following:

我想编写一个程序,它通过 JDBC 自动创建 RDBMS 表。要将列添加到表中,我需要知道列的名称和列的 RDBMS 数据类型。我已经有了列的名称。我没有列的 RDBMS 类型,但我有这些列的 Java 类型。所以我需要将这些 Java 类型映射到 RDBMS 数据类型。Java 类型可以是以下之一:

  • primitve types
  • wrapper types of primitive types
  • String

  • So my question is: How to map those java types to RDBMS types?

  • Is there a part of JDBC or library that already handles this mapping?
  • Are there any classes which can help me partially?
  • 原始类型
  • 原始类型的包装类型
  • 细绳

  • 所以我的问题是:如何将这些 java 类型映射到 RDBMS 类型?

  • 是否有一部分 JDBC 或库已经处理了这个映射?
  • 是否有任何课程可以部分帮助我?

Especially I am working with PostgreSQL. So if there is no genenic way to do it, it would be important for the moment to get it running with PG.

特别是我正在使用 PostgreSQL。因此,如果没有通用的方法可以做到这一点,那么在这一刻让它与 PG 一起运行是很重要的。

Thanks in advance

提前致谢

回答by Steven Fines

Well, there there's always the java.sql.Typesclass which contains the generic SQL type mappings, but you'd be better served using something like Hibernateto do all of this for you.

好吧,总是有包含通用 SQL 类型映射的java.sql.Types类,但最好使用Hibernate 之类的东西为您完成所有这些。

回答by a_horse_with_no_name

getTypeInfo()is intended to get the driver's view on which (native) DBMS type should be mapped to which JDBC type. But these mappings aren't always precise so you will need to find some way of detecting the "best match"

getTypeInfo()旨在获取驱动程序关于应将哪个(本机)DBMS 类型映射到哪个 JDBC 类型的视图。但是这些映射并不总是精确的,因此您需要找到某种方法来检测“最佳匹配”

回答by ftr

Sun/Oracle's JDBC Guide proposes some mappings:

Sun/Oracle 的 JDBC Guide 提出了一些映射:

Mapping SQL and Java Types

映射 SQL 和 Java 类型

回答by JB Nizet

I don't think there is any generic way to do it. The devil is in the details : do you want to impose any precision or scale? What's the maximum number of chars in your strings?

我认为没有任何通用的方法可以做到这一点。魔鬼在细节中:您想强加任何精度或规模吗?字符串中的最大字符数是多少?

The mapping, in its simplest form could be

映射,以其最简单的形式可以是

Java char    --> varchar(1)
Java String  --> varchar
Java number  --> numeric
Java boolean --> boolean