0

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?

Ali Hatami
  • 144
  • 10

1 Answers1

1

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

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
  • Thank you! It works, but another question: How can I handle the pool limit? – Ali Hatami May 14 '20 at 20:38
  • You mean the connection pool limit? That depends what data source you are using. If you use Spring Boot, here is a similar question: https://stackoverflow.com/questions/25573034/spring-boot-how-do-i-set-jdbc-pool-properties-like-maximum-number-of-connection – Christian Beikov May 14 '20 at 20:40