Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate update to null, then try to delete by updated column

I want just that those attributes which are not used will get removed from DB (orphanRemoval=true). What I got is that it first tries to update the refrence PRODUCT_ID and then delete its. but as the refrence is part of the key it cannot.

Parent:

    @Entity
    @Table(name = "STYLE")
    public class Style implements IterableById, Serializable {
    ...
        @OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true)
        @JoinColumn(name="PRODUCT_ID", referencedColumnName = "PRODUCT_ID")
        private List<Attribute> attributes;
    ...

Its Child

    @Entity
    @Table(name="ATTRIBUTE")
    public class Attribute{
        @EmbeddedId
        private Id id;
        ...

        @Embeddable
        public static class Id implements Serializable{

        private static final long serialVersionUID = -8631874888098769584L;

        @Column(name="PRODUCT_ID")
        protected Long productId;

        @Column(name="NAME")
        protected String name;

        @Column(name="COUNTRY_CODE")
        protected String countryCode;
        ...

After i take a list of attributes and clear then, and thtne try to commit i get

    ...
    Hibernate: update ATTRIBUTE set PRODUCT_ID=null where PRODUCT_ID=?
    Hibernate: delete from ATTRIBUTE where COUNTRY_CODE=? and NAME=? and PRODUCT_ID=?
    javax.persistence.RollbackException: Error while committing the transaction
    Caused by: javax.persistence.OptimisticLockException: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    ...

Does anyone know why Hibernate tries to update the reference first, and then deletes it. Can I somehow prevent it from. All I want is that those childs(attributes) which are not used have to get deleted and not just cut the reference. ...

like image 490
MortalFool Avatar asked Jun 03 '14 15:06

MortalFool


1 Answers

I had similar issues. Using "updatable = false" has worked for me.

You can try out below code :

@OneToMany(fetch = FetchType.LAZY,  cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID", updatable = false)
private Set<Attribute> attributes
like image 143
Nebu Avatar answered Oct 03 '22 23:10

Nebu