Search code examples
spring-bootspring-data-jpaquery-by-example

Spring JPA findAll() adding additional columns in where clause


I am new to Spring Boot & JPA. I have an Entity Class as TestEntity which has few fields like testId, name, status etc. and it extends one Base class having generic fields like id, createdBy, lastModifiedBy etc.

Below is the TestEntity class.

@NoArgsConstructor
@Table(name = "TEST")
public class TestEntity extends EntityCommonBase {
    
    @Id
    @Column(name = "TEST_ID", nullable = false)
    private String testId;

    @Column(name = "STATUS")
    private String status;
}

Below is the EntityCommonBase Class :

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class EntityCommonBase {
    @Column(length = 32, columnDefinition = "VARCHAR(32)", unique = true)
    private String id;

    @CreatedDate
    @Column(name = "created", nullable = false, updatable = false)
    private LocalDateTime created;

    @LastModifiedDate
    @Column(name = "last_update")
    private LocalDateTime lastUpdate;

    @CreatedBy
    @Column(name = "created_by", nullable = false, updatable = false)
    private String createdBy;

    @LastModifiedBy
    @Column(name = "last_modified_by")
    private String lastModifiedBy;
}

I am doing findAll() using Example Matcher where I need to find all deals with dealId or with dealId & status.

TestEntity testEntitySearchRequest = new TestEntity();
testEntitySearchRequest.setTestId(testId);
testEntitySearchRequest.setStatus(status.getValue());

Example<TestEntity> example = Example.of(testEntitySearchRequest);
List<TestEntity> tests =  testDAO.findAll(example);

As the input parameters will change and wanted AND condition, I am using Example so that it will generate query dynamically.

Like if I pass only testId in request, findAll will be done with testId in where clause. If I pass testId AND status, then findAll will be done with testId AND status.

This works great and serve my purpose.

But, why it is also adding createdBy & lastModifiedBy in the where clause, I am not understanding.

Any idea why it would add them even if I am not mentioning them to be added in where clause?

Hope the question is clear. Thanks!


Solution

  • Seems like ExampleMatcher can be used to solve this as described here.

    ExampleMatcher matcher = ExampleMatcher.matching()
        .withIgnorePaths("createdBy", "lastModifiedBy");
    
    Example<TestEntity> example = Example.of(testEntitySearchRequest, matcher);
    List<TestEntity> tests = testDAO.findAll(example);
    

    Verified with Spring Boot 3.3 on my computer.