简体   繁体   中英

Hibernate relationship issues on no bidirectional entities

Hi there I have an entity

OfferItem with this two relationship manyToOne

     @ManyToOne
@JoinColumn(name = "offer_id", nullable = false, insertable = false, updatable = false)
@XmlTransient
@Getter
@Setter
private Offer offer;

@ManyToOne
@JoinColumn(name = "item_id", nullable = false, insertable = false, updatable = false)
@XmlTransient
@Getter
@Setter
private Item item;

And the foreign keys configuration on the database

             <addForeignKeyConstraint baseTableName="offer_item"
                             baseColumnNames="item_id"
                             constraintName="item_offer_item_fk"
                             referencedTableName="item"
                             onDelete="CASCADE" onUpdate="CASCADE"
                             referencedColumnNames="id"/>

    <addForeignKeyConstraint baseTableName="offer_item"
                             baseColumnNames="offer_id"
                             constraintName="offers_offer_item_fk"
                             onDelete="CASCADE" onUpdate="CASCADE"
                             referencedColumnNames="id"
                             referencedTableName="offer"/>

the relationship with offer is bidireccional, so on the Offer entity I have this relationship with OfferItem

          @OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL})
@JoinColumn(name = "offer_id", nullable = false)
@XmlElementWrapper
@Getter
private List<OfferItem> offerItems = new ArrayList<>();

On Item I dont have the bidireccional relationship since is not necessary.

Now the problem is, that when I made the set of Item on OfferItem, and I add the offerItem on the OfferItems list of offer, and I save Offer. I can see how the offerItem id is generated because is persisted on cascade. But the link between the offerItem and item is lost.

I just try to set the item on OfferItem and save the entity with his own service, but nothing. I cannot persist this link between them.

Any idea or suggestion.

Regards.

Remove insertable = false, updatable = false from join columns. Also, the mapping for offerItems is wrong. It should be

@OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, mappedBy = "offer")
@XmlElementWrapper
@Getter
private List<OfferItem> offerItems = new ArrayList<>();

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