CodeBender
CodeBender

Reputation: 267

Do I have to try-catch JpaRepository

I am using JpaRepository from Spring Data JPA framework. I have a snippet of code below:

@Repository
public interface PresetFolderRepository extends JpaRepository<PresetFolder, Integer>{

    @Modifying
    @Transactional
    @Query("update PresetFolder pf set pf.parentId = :parentId where pf.id = :id")
    int updateParentId(@Param("id") int id, @Param("parentId") int parentId);
}

When I invoke this method:

@Autowired PresetFolderRepository repo;
    repo.updateParentId(1,2);
public void test(){

Do I have to surround it with a try-catch? How can I know if the self-defined method 'updateParentId' has try-catch implementation in it?

Thanks!

EDIT: My concern is, if my database went down, does this method catch the exception.

Upvotes: 2

Views: 8029

Answers (2)

JB Nizet
JB Nizet

Reputation: 692013

Repositories will always tell you something if a problem happens (i.e. they never swallow exceptions). You'll always get a runtime exception if that's the case.

And you should probably not catch such an exception either, except at the very top of the call stack, where you have the possibility to display an error message to the end user.

Upvotes: 7

Dhanush Gopinath
Dhanush Gopinath

Reputation: 5739

No you don't need it to surround by try-catch block. Most of the Spring-Data repositories throw runtime exceptions. With respect to your concern, if the database is down then a runtime exception is generated and you can catch it at the controller level(if you are writing a web application).

The test case would throw out an error for unreachable host, if you are executing the test case when the DB is down.

Upvotes: 1

Related Questions