Java JPA - 可选列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19098541/
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
JPA - Optional columns
提问by Josh
We have many customers data in separate databases per customer which should have the same schema/table structures. However there is a table that has extra columns in some databases compared to others.
我们在每个客户的单独数据库中有许多客户数据,这些数据应该具有相同的架构/表结构。但是,与其他数据库相比,某些数据库中有一个表具有额外的列。
For example for customer A there is a table X with columns a, b, c, d. For customer B there is a table X with columns a, c, d. I need to capture b if it exists but can ignore it if not.
例如,对于客户 A,有一个包含 a、b、c、d 列的表 X。对于客户 B,有一个包含 a、c、d 列的表 X。如果 b 存在,我需要捕获它,但如果不存在,则可以忽略它。
Is there a way to tell JPA to ignore those columns if they don't exist? @Basic(optional=true)
reads exactly like what I want but the documentation indicates it is for another purpose.
如果这些列不存在,有没有办法告诉 JPA 忽略它们?@Basic(optional=true)
读起来和我想要的完全一样,但文档表明它是出于另一个目的。
Currently I get, as expected, Unknown column 'table.field' in 'field list'
目前,正如预期的那样,我在“字段列表”中得到了未知列“table.field”
P.S. I can't just add the columns to the databases that don't have them unfortunately.
PS,不幸的是,我不能将列添加到没有它们的数据库中。
采纳答案by Alonso Dominguez
@Basic(optional=true)
it's just to tell the schema generator (if any) that the field can hold null values, not that the field might or might not be present.
@Basic(optional=true)
它只是告诉模式生成器(如果有)该字段可以包含空值,而不是该字段可能存在或不存在。
A possible solution for your problem that comes to my mind is to use a class hierarchy, defining a common parent class with @MappedSuperclass
instead of @Entity
and then defining each concrete class for each database extending from that one.
我想到的问题的一个可能解决方案是使用类层次结构,定义一个公共父类,@MappedSuperclass
而不是@Entity
然后为从该数据库扩展的每个数据库定义每个具体类。
With @MappedSuperclass
the JPA implementation wouldn't look for a table to match those fields so you might even have some empty entity classes(extending the super class) just to define your model.
使用@MappedSuperclass
JPA 实现不会寻找匹配这些字段的表,因此您甚至可能有一些空实体类(扩展超类)来定义您的模型。