Home > Net >  Spring JPA Pagination with only boolean check on field
Spring JPA Pagination with only boolean check on field

Time:12-16

I have an entity called Skill which has is_deleted boolean value default to false.

@Repository
public interface SkillRepository extends JpaRepository<Skill, Long> {
    Page<Skill> findAllByOrderByDisplayOrderAsc(Pageable pageable);
}

I want to filter out skills that has is_deleted true with pagination. How to do this? Thanks.

CodePudding user response:

You can use the @Column annotation in your model class to map a field to the is_deleted column and use that field in your repository method.

Add something like this in your Skill class (model)

...
@Column(name = "is_deleted")
boolean deleted;
...

and then you can use the field to search for in the repository like below:

Page<Skill> findByDeleted(boolean isDeleted, Pageable pageable);

CodePudding user response:

Assuming the property looks like this:

boolean deleted

public boolean isDeleted(){
    return deleted;
}

public void setDeleted(boolean deleted) {
    this.deleted = deleted;
}

The following should work.

public interface SkillRepository extends JpaRepository<Skill, Long> {
    Page<Skill> findAllByDeletedIsFalseOrderByDisplayOrderAsc(Pageable pageable);
}

If your property is actually named is_deleted and not just the column things might get tricky, and I highly recommend to switch to standard Java naming conventions.

You can find a list of possible predicates here: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#appendix.query.method.predicate

  • Related