farrellmr
farrellmr

Reputation: 1905

Defaulting a value on a spring data jpa query?

I have a table with a logical deleted field -

CREATE TABLE DOCUMENT 
(
  ID VARCHAR2(255 BYTE) NOT NULL,
  DOCUMENT_NAME VARCHAR2(255 BYTE),
  DELETED NUMBER
)

And I create the JPA object -

@Entity(name = "DOCUMENT")
public class Document {

    @Column(name = "ID")
    private String id;

    @Column(name = "DOCUMENT_NAME")
    private String name;

    @Column(name = "DELETED")
    private Boolean deleted;

    // other params

}

With a repository -

public interface DocumentRepository extends CrudRepository<Document, String> {
    Document findByIdAndDeleted(String id, Boolean deleted);
}

I am only wanting to do lookups of non-deleted documents, so was wondering if there was a way to default my query to deleted = false, and allow me to have repository searches like

// where deleted = false
Document findById(String id);

Upvotes: 1

Views: 381

Answers (2)

dmitrievanthony
dmitrievanthony

Reputation: 1561

If you use Hibernate you can add @Where annotation to your class. Like this:

@Where(clause="deleted <> '1'")
@Entity(name = "DOCUMENT")
public class Document {

    @Column(name = "ID")
    private String id;

    @Column(name = "DOCUMENT_NAME")
    private String name;

    @Column(name = "DELETED")
    private Boolean deleted;

    // other params

}

Take a look here http://featurenotbug.com/2009/07/soft-deletes-using-hibernate-annotations/.

Upvotes: 1

Vladimir
Vladimir

Reputation: 9743

It might get messy, but I believe you can use

Document findByIdAndDeletedIsFalse(String id);

for spring data repositories (reference).

Upvotes: 4

Related Questions