What kind of return from a select count (*) in Spring JPA?

4

I need to know the type of return that Spring JPA returns to put in the Service package, because it is giving NullPointerException :

Dao:

public interface PlaylistDao extends JpaRepository<Playlist, Long> {
    @Query("select count(*) from Playlist")
    public int verifica();
}

Service:

@Service
@Transactional
public class PlaylistServiceImpl implements PlaylistService {

    @Autowired
    private PlaylistDao dao;

    public int verifica(){
        return dao.verifica();
    }
}
    
asked by anonymous 23.11.2018 / 18:47

3 answers

2

The interface JpaRepository (which inherits from CrudRepository ) already comes with a method ready for this action. It is called count() and returns long .

Instead of declaring a new method, you can use this one.

See the documentation for more information. .

    
27.11.2018 / 20:42
1

It returns a Long, due to its count.

TypedQuery<Long>
    
23.11.2018 / 19:24
1

You can use the Spring JPA Repository notation to do count , as igventurelli said:

public interface PlaylistDao extends JpaRepository<Playlist, Long> {

    long count();

}

If you want to count some attribute of the entity, simply add the

long countByName();

If you want to make a count more complex, which involves @Query , you can do:

@Query("SELECT count(*) FROM Playlist")
long countPlaylist();

If you want to use Entity Manager with the following Jpql:

String jpql = "SELECT COUNT(*) FROM Playlist");

You can use TypedQuery<Long >:

TypedQuery<Long> query = entityManager.createQuery(jpql , Long.class);
long total = query.getSingleResult();

Or Number :

Query queryCount = entityManager.createQuery(jpql);
long total = ((Number) queryCount.getSingleResult()).longValue();

To read the final result.

    
10.12.2018 / 19:48