Reputation: 5
Context:
I have two tables Secret_Agent and Secret_Mission. Both have a @ManyToMany
relationship with each other since many secret agents can be given to perform the same secret mission and the same secret agent can be given many secret missions.
Table SECRET_AGENT
Columns SecretAgentId, SecrentAgentName
Table SECRET_MISSION
Columns SecretMissionId, SecrentMissionName
JOIN Table
SECRET_AGENT_MISSION
Columns: SecretAgentId,SecretMissionId
Java Code:
class Secret_Agent {
.
.
.
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "SECRET_AGENT_MISSION", joinColumns = { @JoinColumn(name = "SecretAgentId") }, inverseJoinColumns = { @JoinColumn(name = "SecretMissionId") }
private List <Secret_Mission> missions;
.
.
.
}
class Secret_Mission {
.
.
.
@ManyToMany(mappedBy = "missions")
private List <Secret_Agent> agents;
.
.
.
}
Problem: I am trying to fetch all secret agents who do not have a secret mission assigned through Hibernate Criteria in the below mentioned code:
Criteria criteria = session.createCriteria(Secret_Agent.class);
criteria.add(Restrictions.isNull("missions"));
However, it doesn't work. I am trying my luck with Projections and QBE meanwhile.
Another way is to use the Crieteria Association, but Association would work only with @OneToMany
and @ManyToOne
!
Please help me here.
Upvotes: 0
Views: 257
Reputation: 18383
I'm assuming your mapping is correct: use Restrictions.isEmpty("missions") - Constrain a collection valued property to be empty
(from javadoc)
PS: In Hibernate is best pratice to init collection in mapping as:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "SECRET_AGENT_MISSION", joinColumns = { @JoinColumn(name = "SecretAgentId") }, inverseJoinColumns = { @JoinColumn(name = "SecretMissionId") }
private List <Secret_Mission> missions = new ArrayList<Secret_Mission>();
and do the same for Secret_Agent.agents
Upvotes: 1