简体   繁体   中英

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);

It might get messy, but I believe you can use

Document findByIdAndDeletedIsFalse(String id);

for spring data repositories ( reference ).

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/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM