Herr Derb
Herr Derb

Reputation: 5367

How to query for entities by their string collection values LIKE

I have the following entity:

@Entity
public class SystemLogEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private long creationTime;
    private String thread;
    private int severity;
    @Lob
    private String message;
    @ElementCollection(fetch = FetchType.EAGER)
    @Lob
    private List<String> stacktrace;

    ...
}

My Respository implements JpaSpecificationExecutor, which allows me to use Specifications to filter my db requests:

@Repository
public interface SystemLogRepository extends JpaRepository<SystemLogEntity, Long>, JpaSpecificationExecutor<SystemLogEntity> {

     public List<SystemLogEntity> findAll(Specification spec);
}

For the simple field of the SystemLogEntity this works fine, the Predicate are straight forward.

Also if I filter for an exact item in a collection, the Predicate are still straight forward (in).

But how can I filter my SystemLogEntity after a stack trace collection item which is LIKE a given value?

In other words, I would e.g. like to filter SystemLogEntity after the term NullpointerException. Is this even possible with Predicate?

Upvotes: 1

Views: 182

Answers (1)

Cepr0
Cepr0

Reputation: 30349

I hope this will work:

Specification<SystemLogEntity> stacktraceLike(String stacktrace) {
    return (root, query, cb) -> cb.like(root.join("stacktrace"), "%" + stacktrace + "%");
}

More examples...

Upvotes: 2

Related Questions