开发者

generate id for self referencing table hibernate mapping

开发者 https://www.devze.com 2023-03-29 15:25 出处:网络
Hi I have a table on DB2 database as follows: id (PKey) doc_id(FKey pointing to id) not null This is a strange legacy table that I cannot change. I cannot write/modify triggers either.

Hi I have a table on DB2 database as follows:

id (PKey) doc_id(FKey pointing to id) not null

This is a strange legacy table that I cannot change. I cannot write/modify triggers either.

I am trying to create a hibernate mapping for this table but I can't figure out how to write this odd relationship.

I have two options: 1- tell Hibernate to leave id and doc_id as null then a trigger will set the values for me.

2- figure out a way to tell hibernate to use the sequence to set the values for both values at once.

I cannot seem to find a way to tell hibernate to do this?

any help is greatly appreciated.

<id name="id" type="java.lang.Long" column="ID">
        <generator class="sequence">
            <param name="sequence">SQ_DCMNT</param>
        </gene开发者_JAVA技巧rator>
</id>

<property name="packageDcmntId" generated="insert">
        <column name="PACKAGE_DCMNT_ID" not-null="true"/>
</property>


I would configure this entity to use a custom subclass of SequenceGenerator or SequenceHiLoGenerator to generate its ID. This custom subclass would override the generate method like this:

@Override
public Serializable generate(final SessionImplementor session, Object obj) {
    Serializable result = super.generate(session, obj);
    ((MyBizarreEntity) obj).setPackageDcmntId((Long) result);
    return result;
}

This way, the entity's property will automatically have the value of the generated ID, before the insert is made, which is necessary since the column has a not null constraint.

I've not tested it, but it should work.

Or you could just use a regular sequence generator for the ID, make sure that the access type is property and not field, and implement the setId method like this:

/**
 * Sets the ID as well as the packageDcmntId, since they share the same value
 */
public void setId(Long id) {
    this.id = id;
    this.packageDcmntId = id;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号