Search code examples
javahibernatejpajunitspring-orm

Write junit for JPA repository


Hi I need to write junit test cases for JPA repository. Code is as below.

Test is written as below. I have already added @ContextConfiguration on the class.

@Autowired
@Qualifier("repository")
private Repository repository;

@Test
public void testCreate() {
    Object objRequest = getObjForRequest();
    Object obj = repository.create(objRequest);
    assertTrue(obj.getId().equals(objRequest.getId()));
}

private Object getObjForRequest() {
    Object obj = new Object();

    obj.setId(1);

    return obj;
}

My Repository is written as below.

@Repository("repository")
public class Repository implements RepositoryInterface {

      @PersistenceContext
      private EntityManager entityManager;

      @Transactional(value = "springJpaTransactionManager")
      @Override
      public Object create(Object obj) {
             Object ob = obj;
             entityManager.persist(ob);
             entityManager.flush();
             return ob;
      }
}

When I am running test case it is giving me below error.

javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist:com.*.*.Object

Can anybody help me resolving this.

Thanks


Solution

  • remove setId from :

    private Object getObjForRequest() {
        Object obj = new Object();    
        obj.setId(1);    
        return obj;
    }
    

    you shouldn't set id , as id generated when object become persisted id DB. When you call repository.create(objRequest) with id , spring data do check what it should be - creation new object or update existed , and this check is based on id!=null;

    you should check :

       assertNoNull(obj.getId());
       assertTrue(obj.getId().longValue()>0);
    

    you can compare that id as expected only where you update some existed entity.