How do I resume the amount of Spring JPA records?

Asked

Viewed 451 times

0

I want to return the value of playlists at the bank, but that code there did not work.

public interface PlaylistDao extends JpaRepository<Playlist, Long> {

    @Query("select count(*) from Playlist")
    public int verifica();
}

@Service
@Transactional
public class PlaylistServiceImpl implements PlaylistService {

    @Autowired
    private PlaylistDao dao;

    public int verifica(){
        return dao.verifica();
    }
}
  • tries to change from "int" to "Long" on the return of your method.

  • @Adrianogomes How would that help? A int goes up to 2.147.483.647, right?

  • 1

    Henrique, please specify what you mean by "this code didn’t work". Doesn’t it compile? Error returns? Zero returns? Returns a number nothing to do with the expected?

  • 1

    @LINQ The return of Count in Hibernate is a Long and not an integer, so I believe that Spring jpa behaves the same way.

  • @Adrianogomes Now it makes sense =D

  • I switched to Long, and tested:public Static void main(String[] args) { Playlistserviceimpl se=new Playlistserviceimpl(); System.out.println(se.verifies(); }

  • Gives a java.lang.Nullpointerexception

  • 1

    Your test is wrong. You can’t use new PlaylistServiceImpl(), this way dependency injections are not made. Read this article to better understand: Injection of Dependencies with Spring

  • Try @Query("select count(p) from Playlist p") and let me know if it works.

  • Gave Nullpointerexception , I have to know the type of return I put

Show 5 more comments

1 answer

0

That answer is the same as the other question similar created by the same contributor. However, since it was not marked as duplicate yet, I answered here as well. I am suggesting as duplicate now.

The interface JpaRepository (who inherits from CrudRepository) already comes with a ready method for this action.
He calls himself count() and returns a long.

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

See the documentation for more information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.