i am currently facing a problem within my application and would highly appreciate if somebody has an idea how to solve it.
I have two DB Tables
Item
--------------
OrderID
Status
Detail
---------------
OrderId
Status
Price
Within my app i have two entities
@Entity
@Table(name = "Item")
@IdClass(ItemKey.class)
public class Item {
@Column(name="OrderId")
private String orderId
@Column(name="Status")
private String status
@OneToOne
@JoinColumn(name="OrderId", referencedColumnName="OrderId")
@JoinColumn(name="Status", referencedColumnName="Status")
private Detail detail
}
And the second Entity
@Entity
@Table(name = "Detail")
@IdClass(ItemKey.class)
public class Detail{
@Column(name="OrderId")
private String orderId
@Column(name"Status")
private String status
@Column(name"Price")
private double price
}
I have in the DB a Forgein Key (OrderId, Status) referring from Details to Item Table. Now i have the issue if i am trying to create a Object: Item
including a nested Object Detail
and trying to save them via the ItemRepository
i am getting an error message that related key is not available.
Reason i guess is that internally Hibernate saves first the child and then the parent, so no key would be available at that time.
I could manage to fix the problem by adding in the Entity: Detaila bi-directional mapping and added in Items
the mappedBy
argument in the @OneToOne
Annotation. Unfortunately i dont like the solution because then i would have the attribute always on the Detail Entity which isnt really required and needed.
Does anybody has an idea how to get this working via a unidirectional relation. i tried already @MapsId
and @PrimaryKeyColumnJoin
but same result.
You would have to show us the code you use for persisting, but maybe you are calling entityManager.persist(detail)
before entityManager.persist(item)
? Hibernate does not konw about the ordering. Anyway, I would suggest you use embedded ids instead as id class support has some rough edges.
@Entity
@Table(name = "Item")
public class Item {
@EmbeddedId
private ItemId id = new ItemId();
@OneToOne(mappedBy = "item")
private Detail detail;
}
@Embeddable
public class ItemId {
@Column(name = "OrderId")
private String orderId;
@Column(name = "Status")
private String status;
}
@Entity
@Table(name = "Detail")
public class Detail{
@OneToOne
private Item item;
@Column(name = "Price")
private double price;
}
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.