1

Does an equivalent for the Hibernate filters exist in the JPA? The following hibernate annotation can be for example used in order to define a filter:

@Entity
@FilterDef(name="minLength", parameters=@ParamDef( name="minLength", type="integer" ) )
@Filters( {
    @Filter(name="betweenLength", condition=":minLength <= length and :maxLength >= length"),
    @Filter(name="minLength", condition=":minLength <= length")
} )
public class Forest { ... }

I would like to use something equivalent from JPA in order to restrict read access to some entities. How it can be done using clean JPA, without Hibernate annotations?

I didn't find any serious and reliable solution. I analysed the "JPA Security" project. However, its home page was last updated two years ago, its last version is 0.4.0 and it doesn't seem to be a reliable solution. It's not a standard and it is not popular.

Other alternative in Hibernate which can be used in my case to restrict read access to an entity is the Hibernate Interceptor API - the following interface method can be implemented in order to append a SQL string which contains some additional conditions:

org.hibernate.Interceptor.onPrepareStatement(String sql)

or the following method can be overriden:

org.hibernate.EmptyInterceptor.onPrepareStatement(String sql)

I found out that there are some JPA event callbacks and annotations, e.g. @PostLoad. However, none of these can be used in my case, because I need something to restrict access to entities based on some conditions (user role).

Anyone knows how it can be done using JPA standards?

4

1 回答 1

0

在我看来,您正在尝试对实体对象执行验证。你有几个选择来完成这个。

第一种是使用Java Validations API及其相关的验证。这是 Java EE 的推荐方法,其中 JPA 是其中的一部分。例如,您可以按如下方式编写实体类:

@Entity
class Person {
  @NotNull
  @Size(min = 5, Max = 50)
  String name;
}

现在,每次您尝试持久化 的实例时Person,JPA 提供程序都会自动验证该实例,前提是类路径上有一个 Java Validator。验证错误将作为运行时异常抛出,并可用于回滚事务。也可以手动调用验证器,收集任何验证错误并在需要时将它们转换为用户友好的消息。

另一个(可能是脏的)选项是使用 JPA 事件侦听器,执行验证并在验证失败时抛出异常。这将立即终止 JPA 操作并回滚任何事务。

于 2014-02-14T04:24:53.620 回答