O.Zaytoon
O.Zaytoon

Reputation: 1

Detached entity passed to persist Error in spring jpa With Scheduler threads

i have getting this exception when i try to save and flush Object From Class A. (spring version 2.7.8)

@Table(name= "table_a")
@Entity
@Data
public class A {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

@ManyToOne(optional = false, targetEntity = B.class, cascade = CascadeType.PERSIST)
private B b;
//...etc
}

and class B:

@Table(name= "table_b")
@Entity
@Data
public class B {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
//...etc
}

my code block:

public void saveData(A a){
aJpaRepository.saveAndFlush(a);
}

when saveData invoked from Api Call Request its work and cascaded correctly, but when I call it with same object from scheduler thread it occurred this exception:

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.example.model.B; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.model.B
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:297)

solution and explaining for this behavior?

Upvotes: -1

Views: 74

Answers (2)

O.Zaytoon
O.Zaytoon

Reputation: 1

The solution was by add the following block of code:

@PersistenceContext
private EntityManager entityManager;

@Transactional
public A saveA(A a) {
  a.setB(entityManager.merge(a.getB));
  return aJpaRepostiory.saveAndFlush(a);
}

Thanks for your help

Upvotes: 0

crizzis
crizzis

Reputation: 10716

Transactions (and by extension, JPA units of work) are thread local in Spring. They do not propagate across different threads.

This means when you're trying to save the entity from a separate thread, it is seen as detached. You have to make sure you have Cascade.MERGE declared on the association from A to B.

Even with this issue fixed, remember that there is no transaction spanning both threads, which may affect the correctness of your business logic.

Upvotes: 0

Related Questions