-1

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?

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, i have add merge to cascade type but unfortunately, same issue occurred. but your answer lead me to the solution so thanks a lot
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.