我们有很多表,列的定义方式如下:
create table tbl_1 (
id int primary key,
-- ... a lot of specific stuff skipped
reserved_1 char (10), -- byte 1: flag_A
-- byte 2-5: value_B
-- byte 6: flag_C
-- byte 7-8: value_D
-- byte 9-10: not used
-- flag_A, value_B, flag_C, value_D
-- have no relations to each other in general
reserved_2 char(10), -- ....
);
我想将它映射到类中,如下所示:
@Entity
@Table(name = "TBL_1", uniqueConstraints = @UniqueConstraint(columnNames = "ID"))
public class Tbl1 implements java.io.Serializable {
private int id;
// irrelevant properties skipped
private String flagA;
private String valueB;
private String flagC;
private String valueD;
// getters/setters will follow
}
Hibernate有可能吗?据我所知,这是可能的 使用UserType将它们组合成单个列,如下所示(简化):
public class Tbl1 implements java.io.Serializable {
private int id;
// irrelevant properties skipped
private Reserved1 reserved1;
}
public class Reserved1 implements java.io.Serializable {
private String flagA;
private String valueB;
private String flagC;
private String valueD;
}
但我想隐藏对reserved1列/属性的所有引用 并且仅为flagA,valueB,flagC,valueD公布getter / setter 彼此无关,所以将其与课堂相结合是一个坏主意,并且 保持未来(希望)表重组的灵活性。可能吗 在Hibernate?
答案 0 :(得分:0)
好的,实际上很简单:只需为fetch,update和insert定义自定义查询:
@SQLUpdate (sql = "UPDATE tbl_1 SET oth_col=?, reserved_1=(substring(?||' ' from 1 for 1) || substring(?||' ' from 1 for 4) || substring(?||' ' from 1 for 1) || substring(?||' ' from 1 for 2) where id=?")
@SQLInsert (sql = "define it the same way as update")
@Loader (namedQuery = "tbl_1_ldr")
@NamedNativeQuery (name="tbl_1_ldr", query="SELECT id,..., substring(reserved_1 from 1 for 1) as flag_a, substring(reserved_1 from 2 for 4) as value_b, substring(reserved_1 from 6 for 1) as flag_c, substring(reserved_1 from 7 for 2) as value_d FROM tbl_1 WHERE id = ? ")