java 枚举 sql,如何在数据库中建模(Java)枚举(使用SQL92)

Hi am modelling an Entity with a column named "Gender". In the application code, the gender is supposed to be an (Java) Enum type, with 2 values (MALE and FEMALE).. how would you model it, knowing that Enums as Datatype are not part of the generic SQL (language) 92.

It the data model would have to be portable, in order to be used by several DBMS (Mysql, Oracle, Derby) and several persistence provider (JPA, Hibernate, JDBC).

I feel, it hits at 2 levels:

- first the level of the Schema and the entity (store the enums as -VAR-CHAR or INT)

- second the level of the app code (JDBC doesn't support enums, JPA does but it depends on the implementation)

Is there a generic solution, applicable for example to an Mysql DBMS ?

Thanks !!

解决方案

I typically adopt the following solution, which gives a fully normalised database schema.

Create a dedicated table to represent your enumeration; e.g. Colour. The table will have two columns:

An ID column (primary key). Typically an auto-incrementing int, smallint or tinyint.

A name column (candidate key). This will be a varchar whose value should be identical to the Java enumeration.

Create a Java enum: Colour with identical values to the Colour table in the database.

Assuming you now have a "Data" table containing records that reference the Colour table, implement a stored procedure for inserting a record, which takes the Colour String value (as described by your Java enum); e.g.

CREATE PROCEDURE dbo.InsertRecord

@colour varchar(32)

AS

...

The stored procedure will perform the necessary String-to-int translation allowing your data table to reference a the Colour table via an int foreign key.

Similarly you can create a view onto your data table(s) that will join to the Colour table behind the scenes to present a denormalised via of your data back to the application or end user.

The alternative to the stored procedure approach is that you read and cache the ordinal, name mappings within your application on startup. This has the advantage of being able to verify the integrity of your Java Colour enum compared with the contents of your Colour table in the database.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值