简体   繁体   中英

How do you update a foreign key value directly via Hibernate?

I have a couple of objects that are mapped to tables in a database using Hibernate, BatchTransaction and Transaction. BatchTransaction's table (batch_transactions) has a foreign key reference to transactions, named transaction_id.

In the past I have used a batch runner that used internal calls to run the batch transactions and complete the reference from BatchTransaction to Transaction once the transaction is complete. After a Transaction has been inserted, I just call batchTransaction.setTransaction(txn), so I have a @ManyToOne mapping from BatchTransaction to Transaction.

I am changing the batch runner so that it executes its transactions through a Web service. The ID of the newly inserted Transaction will be returned by the service and I'll want to update transaction_id in BatchTransaction directly (rather than using the setter for the Transaction field on BatchTransaction, which would require me to load the newly inserted item unnecessarily).

It seems like the most logical way to do it is to use SQL rather than Hibernate, but I was wondering if there's a more elegant approach. Any ideas?


Here's the basic mapping.

BatchQuery.java

@Entity
@Table(name = "batch_queries")
public class BatchQuery
{
    @ManyToOne
    @JoinColumn(name = "query_id")
    public Query getQuery()
    {
        return mQuery;
    }
}

Query.java

@Entity
@Table(name = "queries")
public class Query
{
}

The idea is to update the query_id column in batch_queries without setting the "query" property on a BatchQuery object.

Using a direct SQL update, or an HQL update, is certainly feasible.

Not seeing the full problem, it looks to me like you might be making a modification to your domain that's worth documenting in your domain. You may be moving to having a BatchTransaction that has as a member just the TransactionId and not the full transaction.

If in other activities, the BatchTransaction will still be needing to hydrate that Transaction, I'd consider adding a separate mapping for the TransactionId, and having that be the managing mapping (make the Transaction association update and insert false).

If BatchTransaction will no longer be concerned with the full Transaction, just remove that association after adding a the TransactionId field.

As you have writeen, we can use SQL to achieve solution for above problem. But i will suggest not to update the primary keys via SQL.

Now, as you are changing the key, which means you are creating alltogether a new object, for this, you can first delete the existing object, with the previous key, and then try to insert a new object with the updated key(in your case transaction_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM