Chandru
Chandru

Reputation: 1014

Spring data JPA save method returns null

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?

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);
}

Upvotes: 2

Views: 10020

Answers (1)

user1053510
user1053510

Reputation: 1677

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);

Upvotes: 1

Related Questions