Reputation: 9333
Suppose I have classes somewhat like the following (getters/setters ommitted for brevity).
public class Record{
// ... properties
private Metadata metadata;
@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
public Metadata getMetadata(){
return metadata;
}
}
public class Metadata {
private Boolean enabled = false;
private Record record;
@OneToOne
@PrimaryKeyJoinColumn
public getRecord() {
return record;
}
@Column("enabled")
public Boolean getEnabled() {
return enabled;
}
}
Using hibernate criteria I want to run a query that says ' Give me all of the records that have null metadata or metadata that is not enabled'. For the time being my code does the following:
List results = session().createCriteria(Record.class).list();
// iterate over results, pluck out the Records that match my criteria
... but we can do better right?
I've tried creating an alias of metadata and attempting to see if the alias is null, or if the alias.property matches my condition i.e. (Restrictions.eq("metadata.enabled", false) but that doesn't work. I also attempted to use a disjunction to filter my results by the two conditions i'm looking for (metadata is null, or metadata is not enabled). Neither of these approaches worked; I assume its because what I'm trying to do with criteria isn't joining in the manner I expect it to. Please shed some light on this for me if you can.
Upvotes: 1
Views: 4908
Reputation: 702
Maybe something like this:
Criteria crit = session().createCriteria(Record.class);
crit.add( Restrictions.disjunction()
.add( Restrictions.isNull("metadata") )
.add( Restrictions.eq("metadata.enabled", false) )
);
List results = crit.list();
Or this:
List results = session().createCriteria(Record.class)
.add( Restrictions.or(
Restrictions.eq( "metadata.enabled", false ),
Restrictions.isNull("metadata")
)).list();
Upvotes: 2