问题
I have annotated a Hibernate entity with a @Where attribute at the class level. This restricts which entities are loaded when I query it directly, but it does not seem to be applied to collections of that class. Is that to be expected?
The docs are not clear on this: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-class
where (optional): specifies an arbitrary SQL WHERE condition to be used when retrieving objects of this class.
That sounds to me like it applies to all cases where objects of that class are retrieved, but I have observed this being ignored for collections.
- Is this meant to work for collections?
- If not, what is the best way to globally apply a filter to all instances of a class, and all collections of that class?
(UPDATE: I raised https://hibernate.atlassian.net/browse/HHH-6781 to track the doc issues.)
回答1:
@Where at the class level will omit the unwanted instances when using "getAll" or "loadAll". Having @Where at the class level will not "cascade" to apply to the collections on that entity.
@Where at the collection property level public class PuppySeller {
@Where(clause = "status='FOR_SALE'")
public Set<Puppy> getPuppiesForSale() {}
will ensure that when you select "PuppySeller" from the DB, "puppiesForSale" will only be populated by puppies with the "FOR_SALE" status.
However, be very cautious, because it only applies for first level collections. What I mean by this, is that say you have a puppy, and you want to get all puppies for sale by the same seller. You might do something like "myPuppy.getPuppySeller().getPuppiesForSale()". However, if you do this, you will end up with all puppies, regardless of status, that belong to the puppySeller, including all puppies that are "SOLD" or "NEWBORN", etc.
来源:https://stackoverflow.com/questions/7892665/hibernate-class-level-where-annotation-is-not-enforced-on-collections-of-that