Hibernate 3.0 中的条件映射?
如何在 hibernate 中创建依赖于 type 属性的映射,将数据插入适当的列或从适当的列检索数据。
结构:
表列:
|TYPE | CHARACTER | DATE | TIME | NUMERIC|
POJO:
class Pojo {
private int type;
private Object data;
...
}
示例:
插入/更新
如果类型为 1,我们将值输入到列 CHARACTERSelect
如果类型为 2,我们从 NUMERIC 列获取值
如果类型为 2,我们从 NUMERIC TIP : 我们有两列并且对结果进行透视的结构不适合这种情况。
How to create mapping in hibernate that depends on the type property, insert/retrieve the data into/from proper column.
Structure:
TABLE COLUMNS:
|TYPE | CHARACTER | DATE | TIME | NUMERIC|
POJO:
class Pojo {
private int type;
private Object data;
...
}
Examples:
Insert/Update
If the type is 1 we input the value to column CHARACTERSelect
If the type is 2 we get the value from column NUMERIC
TIP:
The structure where we have two columns and we PIVOT the result is not a option for this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我为此选择的解决方案是使用整数鉴别器映射每个类层次结构的表。
我创建了一个基本的抽象泛型类,用于存储
我创建的类型管理对象和接口,但可以使用 Arthur 提出的封装进行枚举。
对于我创建的每种类型,类
提示:为了允许使用数字作为鉴别器值,我们需要首先为我们正在映射的类指定它,因为默认情况下使用类名 [String],并且我们尝试使用子类映射的数字鉴别器我们会得到一个休眠错误,说存在某种类型不匹配。
虽然我们从数据库检索对象始终位于给定类型的类中,但我们可以轻松地对其进行操作,并且我们通过保存基类来使用一个位置来保存它们。
The solution that i have choose for this is table per class hierarchy mapping with an integer discriminator.
I have created a base abstract generic class that store the object
For Type management i have created and interface, but there is possible to enumeration using the encapsulation presented by Arthur.
The for each type I have created class
TIP: To allow use the a number as discriminator value we need to specify it first for the class that we are mapping, because by default is used class name [String] and i we try to use the numeric discriminator for subclass mapping we will get a hibernate error say that there is some type mismatch.
While we retrieve the object from database is always in given typed class that we can operate easily on it, and we use one place to save them by saving the base class.
这种行为是通过使用封装来实现的。例如,我在数据库(INSERT/UPDATE)中有一个字符串(Y/N)列,它由布尔值(SELECT)封装,如下所示。
您的映射位于此处
此策略已解释此处 我使用了除了转换之外的解决方法,以允许 String Java 关键字用作枚举。请参阅此处
This kind of behavior is accomplished by using encapsulation. For instance, i have a String (Y/N) column in database (INSERT/UPDATE) which is encapsulated by a boolean (SELECT) as follows
Your mapping goes here
This strategy is explained here I have used, besides conversion, as a workaround To allow String Java keywords To be used as Enum. See here