如果不存在,Hibernate会忽略列 [英] Hibernate ignore column if not exist

查看:114
本文介绍了如果不存在,Hibernate会忽略列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是,我有一个应用程序,使查询不同的数据库,和一些实体有丢失的列。有没有办法忽略丢失的列而不使用继承?

解决方案

有不同的可能性取决于您的需求:


  1. 如果你从不需要这些额外的列,它们只存在于某些数据库中,那么你就不要在映射中(或在注释中)定义它们。然后它们从不被Hibernate读取,并且在插入时列被设置为null(如果你想让值不同于null,你可以在数据库中定义默认值或者触发器)。


  2. 如果你需要额外的列时,你需要不同的映射为不同的数据库。对于这种情况,最好使用xml映射文件。无论如何,每个数据库都有一个单独的hibernate.cfg.xml文件(连接字符串在那里)。在这里,对于具有不同列的表,您可以指定不同的映射文件(标记< mapping resource =.../> )。 Java pojo,我。即Java类对于所有数据库都是相同的,并且它包含任何数据库上存在的所有列,但是在数据库特定映射文件中,只将这些列映射到该数据库中真正存在的Java成员。 (注释这很烦人,因为那么你需要不同数据库的不同Java类,并且你必须处理代码中的逻辑。)


  3. 如果表是只读,那么你可以在该表上定义一个数据库视图,并让该视图提供具有缺省值的缺失列。然后在Hibernate中映射视图而不是表格。



Ok the problem is that i have a aplication that make queries to different DB, and some Entities there are missing columns. Is there a way to ignore missing columns without using inheritance?

解决方案

There are different possibilities depending of your needs:

  1. If you never need these extra columns, which exist only in some databases, then you just do not define them in the mapping (or in the annotations). Then they are never read by Hibernate, and on insertion the columns are set to null (you can define default values or triggers in the database if you want values different than null).

  2. If you need the extra columns when they exist, then you need different mappings for the different databases. Better you use xml mapping files for this case. Anyway you have an individual hibernate.cfg.xml for each database (the connect string is in there). In here for the tables with different columns you specify different mapping files (tag <mapping resource="..." />). The Java pojo, i. e. the Java class, is the same for all databases, and it contains all columns which exist on any database, but in the database specific mapping files you only map those columns to Java members which really exist in that database. (With annotations this is annoying because then you need different Java classes for different databases and you have to handle the logic in your code.)

  3. If the tables are read only, then you can define a database view over that table and let this view providing missing columns with default values. Then in Hibernate you map the view and not the table.

这篇关于如果不存在,Hibernate会忽略列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆