Domanda

I have two entities with ManyToOne relationship ( Product and Owner). The problem is that when I try to update the Product entity those fields of it that are not included in the form and the fields of it's owner's entity will be changed to null.

Entities

@Entity
@Table(name = "product")
@DynamicUpdate
public class Prodcut implements Serializable {
    private long id;
    private Owner owner;
    private String code;
    private String name;
    ....

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "owner")
    public Owner getOwner() {
        return owner;
    }

    public void setOwner(Owner owner) {
        this.owner = owner;
    }
}

@Entity
@Table(name = "owner")
@DynamicUpdate
public class Owner implements Serializable {
    private long id;
    ....
}

In this case after update as code is not included in the form will be changed to null, and all fields of owner also will be changed to null.

Update Form

<s:form method="POST" autocomplete="on" action="update">
                <input type="hidden" name="product.id" value="${product.id}"/>
                <s:select name="product.owner.id"
                          id="product.owner.id"
                          label="Owner"
                          list="listOfOwners"
                          headerKey=""
                          headerValue="Owner"
                          value="%{product.owner.id}"
                          />
               <input type="text" name="product.name" value="${product.name}"/>
               ....

Hibernate code

 final Transaction tx = session.beginTransaction();
            try {

                Product product1 = (Product) session.get(Product.class,product.getId());
                Owner owner1 = (Owner) session.get(Owner.class, product.getOwner().getId());
                product.setOwner(owner1);
                product.setCode(product1.getCode);

                if (!tx.wasCommitted()) {    
                      tx.commit();
                }

                return pro;
            } catch (Exception e) {
                tx.rollback();
                e.printStackTrace();
            }

I tried to retrieve the product object from database and replace the values of those fields that are not provided in the form but it runs into an error "a different object with the same identifier value was already associated with the session".

È stato utile?

Soluzione

The last strategy is the good one. You msut simply not call update() or any other method:

Product persistentProduct = (Product) session.get(Product.class, product.getId());
persistentProduct.setName(product.getName());
// copy other fields
// nothing more
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top