【问题标题】:Is it possible for Hibernate to use a class with no default c'tor as a component or composite-element?Hibernate 是否可以使用没有默认 c'tor 的类作为组件或复合元素?
【发布时间】:2011-06-08 20:03:40
【问题描述】:

我需要在 Hibernate 中使用一些遗留类。其中一个类没有默认构造函数,因此我收到“org.hibernate.InstantiationException:实体没有默认构造函数:..”错误。我不需要直接坚持这个类。这是映射:

<class name="test.geo.support.Observation" table="observation">
        <id access="property" column="obs_msg" name="EncodedObMsg" type="string"/>
                <property name="ReportTime" column="report_time" type="long" />
                <many-to-one name="Station" column="station_id" class="test.geo.Station"/>
    </class>
    <class name="test.geo.Station" table="station">
        <id access="property" column="station_id" name="UniqueId" type="string" />
                <component name="Point" class="test.geo.geometry.PointGeometry">
                    <property name="latitude" type="double" access="field" column="lat" />
                    <property name="longitude" type="double" access="field" column="lon" />
                </component>
    </class>

我需要持久化“观察”和“站”,并希望引用“PointGeometry”类来持久化 Station.Point。 'PointGeometry' 没有默认构造函数,有什么方法可以解决这个问题?

【问题讨论】:

    标签: java hibernate hibernate-mapping


    【解决方案1】:

    你总是需要一个无参数的构造函数。如果我真的不喜欢我的代码不调用任何 arg 构造函数,我将其设为 protected

    【讨论】:

    • 无参数构造函数最多可以是包私有
    • @hvgotcodes protected 绝对有效,因为它在我的代码中。但我收回了private。答案已编辑。
    • yes protected 将起作用,因为它比包私有的限制更少。注意“包私有”是一个术语。我没有说私密。
    • 我已将无参数构造函数设为私有,Hibernate 仍然有效
    【解决方案2】:

    不,您需要一个无参数构造函数。 Hibernate 需要一种创建对象的方法。

    您也许可以创建此类的子类,并为子类提供无参数构造函数。

    【讨论】:

      【解决方案3】:

      没有。这是 JPA 要求。在 Hibernate 中,您可以实现一个根据需要填充对象的拦截器。见:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-24
        • 1970-01-01
        • 2013-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-24
        • 2018-09-16
        相关资源
        最近更新 更多