Tiim
Tiim

Reputation: 181

Hibernate get remaining objects from many to one relation

I have a database which stores clubs and teams. A club has multiple teams and a team is part of only one club. Is it possible to query all teams which are not in a specific club using the hibernate criteria api? Here are the (stripped) Club.java and Team.java

Club.java

@Entity
@Table(name = "clubs")
public class Club {
    @Id
    @GeneratedValue
    @Column(name = "club_id")
    private int id;
    @Column(name = "name")
    private String name;
    @OneToMany(mappedBy = "club")
    private java.util.Set<Team> teams;

    [setters, constructors etc]
}

Team.java

@Entity
@Table(name = "team")
public class Team {
    @Id
    @GeneratedValue
    @Column(name = "team_id")
    private int id;
    @Column(name = "name")
    private String name;
    @ManyToOne
    @JoinColumn(name = "club_id")
    private Club club;

    [same here]   
}

Upvotes: 0

Views: 82

Answers (2)

olambert
olambert

Reputation: 1115

As a slight variation on the answer above, if you already have the Club object which you wish to find all teams not belonging to it, you should be able to do something like:

Criteria criteria = session.createCriteria(Team.class);
criteria.add(Restrictions.ne("club", myClub));
List<Team> teams = criteria.list();

This avoids having to query on the club name and IMHO is cleaner code.

Upvotes: 1

Gergely Bacso
Gergely Bacso

Reputation: 14651

It should be something like this:

Criteria criteria=session.createCriteria(Team.class);
        .createAlias("club", "c")
        .add( Restrictions.not(Restrictions.like("c.name", "nameOfTheClubIAmLookingFor", MatchMode.EXACT)) )
        List<Team> teams=criteria.list();

Upvotes: 1

Related Questions