2

I am trying to save a new entity with Spring Data JPA and Hibernate from JUnit test case. The save method is returning null. If I run from Eclipse as "Run As JUnit" it is working fine and test is passing. But the same test case with maven test is failing with null pointer because JpaRepository's save method is returning null. Any idea?

  • Spring data - 1.8.0.RELEASE
  • Hibernate - 4.3.8.Final
  • Spring - 4.1.5.RELEASE
  • Maven - 3.2.5
  • Java8, Junit4

Note: I tried both save and saveAndFlush but with no luck.

Service class

Application appl=applicationRepository.saveAndFlush(application);//Returns null 

Repository class

public interface ApplicationRepository extends JpaRepository<Application, Integer> { @Query(nativeQuery = true, value = "select count (ap1.appn_id) cnt from appn ap1 where ...") List<BigInteger> countByCreatedTSLessThanEqual(String date); } 
4
  • are committing the Transaction? Commented Apr 23, 2015 at 4:57
  • Spring data internally has commit still i am commiting explicitly also.so i don't think commit is problem on further analysis even findOne method is also not returning data. Commented Apr 23, 2015 at 18:59
  • Can you share code for your test class? Commented Apr 26, 2015 at 1:50
  • I had this phenomenon in an unrelated matter. It turned out that an N-to-N relationship modeled by a List on the left side was making problems when inserting new objects on the right side because the left side List was updated and saved on two different places in the call stack (I think). Inserting right-side objects worked for a time, then nulls started to be returned. It's good to add appropriate logging statements at the critical places to see what happens. Commented Aug 29, 2017 at 14:27

1 Answer 1

1

We also encountered very similar problem. It was exactly as you described - null after save() or saveAndFlush() and null after findOne().

In our case the reason was an aspect (Spring @Aspect) controlling data being saved via Spring JPA

@Around("execution(public !void org.springframework.data.repository.Repository+.*(..))") 

that filtered out the result. Make sure you have no aspects running around your calls to repository or adjust them if necessary.

As a workaround, we also managed to bypass the aspect by injecting entity manager directly and calling its methods.

@PersistenceContext private EntityManager em; em.joinTransaction(); final Application savedAppl = em.merge(application); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.