Ali Hatami
Ali Hatami

Reputation: 144

how can we update all references of an entity with hibernate?

Is there any way to update all of the references of an entity loaded into our program by hibernate all at time?

for example, I have loaded the product with id "1" in class A and change a new load of the same product with id "1" in class B. but the one in class A didn't change. how should I fix this?

This is part of the code : Product class :

@Entity
@Table(name = "t_product")
public class Product {
    @Setter(AccessLevel.NONE)
    @Id @GeneratedValue @Column(name = "ID")
    private int id;
    ...
    @ElementCollection
        @OneToMany(targetEntity = SellerIntegerMap.class,
                   fetch = FetchType.EAGER,
                   cascade = CascadeType.ALL)
        @JoinTable(name = "t_product_stock")
    private List<SellerIntegerMap> stock;
    ...
}

SellerIntegerMap :

@Entity
@Table(name = "t_map")
public class SellerIntegerMap{
    @Setter(AccessLevel.NONE)
    @Id @GeneratedValue
    private int id;

    @ManyToOne
    @JoinColumn(name = "SELLER")
    private Seller seller;

    @Column(name = "INTEGER_VALUE")
    private Integer integer;
}

DBManager :

public class DBManager {
    public static <T> T load(Class<T> type, Serializable serializable){
        Session session = HibernateUtil.getSession();
        session.beginTransaction();
        T object = session.get(type,serializable);
        if (object == null){

        }
        session.evict(object);
        session.getTransaction().commit();
        return object;
    }

    public static void save(Object object){
        Session session = HibernateUtil.getSession();
        session.beginTransaction();
        session.saveOrUpdate(object);
        session.getTransaction().commit();
    }
}

and the test :

public void test(){
        Product product = DBManager.load(Product.class,1);
        Product productDup = DBManager.load(Product.class,1);
        List<SellerIntegerMap> list = productDup.getStock();
        list.get(0).setInteger(25);
        DBManager.save(productDup);
}

The data is updated in SQL table but not in "product" which is a same entity like "productDup". how can I solve the problem ? is there any way to solve it in the program not loading the data every time we need them?

Upvotes: 0

Views: 665

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16400

You need one transaction over the whole operation. That way, Hibernate will keep only a single managed instance of that entity.

Upvotes: 1

Related Questions