【问题标题】:Over ride default fetch to skip rows with certain values覆盖默认提取以跳过具有某些值的行
【发布时间】:2014-03-31 19:03:44
【问题描述】:

我正在使用 Java、Hibernate、Spring Data 并且对这项技术相当陌生。 我需要弄清楚如何跳过标记为“已归档”的行。我们的数据库架构师严格指导我们不得从数据库中删除任何行。

@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;    
}

在上面的示例中,任何扩展 AbstractEntity 的类都不应返回已归档 == true 的行。我所有的域类都将扩展 AbstractEntity,所以我想要一个在 AbstractEntity.java 中或在某些全局配置中实现的解决方案,以便所有生成的 SQL 调用都是 'where [table]。归档 true'

【问题讨论】:

    标签: java hibernate jpa spring-data-jpa


    【解决方案1】:

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

    我从未使用过 Spring Data,但官方文档的 Adding custom behavior to all repositories 部分让我相信获取注入的 EntityManager 并自定义其行为非常容易。只需打开它并启用过滤器即可。

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

    如果您希望将过滤器应用于@MappedSuperclass 的所有子类,请使用最新版本的 Hibernate。只有 3.5 及更高版本(请参阅 HHH-4332)支持此行为。

    此外,还有一个问题,您可能需要对关联重复过滤(请参阅Hibernate Filters on related table with MappedSuperClass)。


    如果您还想自定义删除操作,请使用@SQLDelete 标记archived = 1(请参阅Soft deletes using Hibernate annotations)。但据我所知,这只适用于映射实体(在@MappedSuperclass 级别无法完成)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2020-06-07
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 2022-01-25
      • 2015-03-13
      相关资源
      最近更新 更多