Alain
Alain

Reputation: 385

Is it possible to have @OneToOne relation between 2 objects but not having the child automatically persisted in Hibernate

I'm using jpa persistance annotations. I have 2 objects, Order(parent) and Transaction(child). I want to be able to fetch my oder and get its transaction. The problem is I don't want my transaction to be automatically saved when I save my order. I need to do some special processing on it before I save it.

Is there a way to tell hybernate not to persist the child object but still fetch it when I retreive the order?

I tried something like this

@OneToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name = "commande_id", insertable=false, updatable=false)

This didn't work. I keep getting this message:

object references an unsaved transient instance - save the transient instance before flushing

When I try to save the order object. The first time I save the order the transaction object contains some data but its not ready to be saved yet.

Thanks in advance

Upvotes: 2

Views: 375

Answers (2)

Ralph
Ralph

Reputation: 120861

You could make the relationship bidiretional and controlled by the transaction side.

Something like

class Order {
  @OneToOne(mappedBy="order", cascade={}, insertable=false, updatable=false)
  private Transaction transaction;
}

class Transaction {
  @OneToOne(name = "order_fk")
  private Order order;
}

If you do it in this way, the the order.transaction shoud have no writing influence to the data base. But even it it works, i belive it is a hack.

Upvotes: 1

digiarnie
digiarnie

Reputation: 23445

What if you detach the Transaction from the Session?

session.evict(transaction);

Not sure if that will work but just an idea.

Upvotes: 1

Related Questions