Pergunta

I am using Java, Hibernate, Spring Data and fairly new to this technology. I need to figure out how to Skip rows that are marked as 'archived.' We have a strict guidance from our DB architect that no rows shall be deleted from the database.

@MappedSuperclass
public class AbstractEntity implements Identifiable<String> {

    @Id
    @GeneratedValue(generator="system-uuid")
    @GenericGenerator(name="system-uuid", strategy="uuid")
    private String id;

    private boolean archived; //<----?
} 

@Entity
public class Employee extends AbstractEntity {        
    private String title;
    private String fullName;
    @ManyToOne
    private Department dept;
}

@Entity
public class Department extends AbstractEntity {        
    private String name;    
}

In the above example, any class extending AbstractEntity should never return rows that have archived == true. All my domain classes will be extending AbstractEntity so I'd like a solution that's either implemented in AbstractEntity.java or at some global configuration so that all generated SQL calls are 'where [table].archived <> true'

Foi útil?

Solução

Take a look at Hibernate Filters.

@FilterDef(name="activeOnly")
@Filter(name="activeOnly", condition= "archived <> 1")
// assumes that all tables have a numeric column "archived"
// as you can notice, this is a filter at the SQL Level 
//  (not at the Entity level)
@MappedSuperclass
public class AbstractEntity // ....

I've never used Spring Data, but the Adding custom behavior to all repositories section of the official documentation lead me to belieave that it is quite easy to obtain an injected EntityManager and customize its behaviour. Just unwrap it and enable the filter.

Session session = entityManager.unwrap(Session.class); 
session.enableFilter("activeOnly");

If you want the filter to be applied for all subclasses of the @MappedSuperclass use a recent version of Hibernate. Only version 3.5 and greater (see HHH-4332) supports this behaviour.

Also, there is one gotcha, you may need to repeat the filter on associations (See Hibernate Filters on related table with MappedSuperClass).


If you want to customize the delete operations as well, use @SQLDelete to mark archived = 1 (see Soft deletes using Hibernate annotations). But to the best of my knowledge this only works on mapped entities (nothing can be done at the @MappedSuperclass level)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top