3

I have a OneToMany relation defined as follows

class ActionSet {
    @OneToMany
    List<Action> action;
}
class Action {
    ActionSet actionSet;
    Boolean isShared;
}

Action can either be shared across many action sets or be associated with a single actionSet.

When an action is shared, it can be important for some action sets but not others. Here isImportant is a relationship property. How can I define that relationship in JPA ?

kranthi117
  • 628
  • 1
  • 8
  • 21

1 Answers1

3

Essentially you will need three entity classes as below:

ActionSet:

@Entity
public class ActionSet {

    @OneToMany(mappedBy = "actionSet")
    List<ActionSetAction> action;
}

Action:

@Entity
public class Action {

    @OneToMany(mappedBy = "action")
    List<ActionSetAction> action;
}

ActionSetAction (representing the Join table):

@Entity
public class ActionSetAction {

    @ManyToOne
    @JoinColumn(name = "action_set_id")
    private ActionSet actionSet;

    @ManyToOne
    @JoinColumn(name = "action_id"
    private Action action;

    @Column(name ="is_important"
    private boolean important;
}

If you want to distinguish between important and unimportant action set actions at the database level rather than in memory then you can look at using the non-JPA Hibernate specific @Where annotation.

@Entity
public class ActionSet {

    @OneToMany(mappedBy = "action")
    @Where(clause="is_important = true")
    List<ActionSetAction> importantActions;

    @OneToMany(mappedBy = "action")
    @Where("is_important = false")
    List<ActionSetAction> unimportantActions;
}

Note that I answered a question recently where I suggested a pure JPA solution to a very similar problem. However, while this worked in EclipseLink there are issues with it in Hibernate.

JPA ManyToMany where annotation

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110
  • Thanks for your detailed answer. My searches ended up with the same result. My only concern is that it'll give rise to 4+ database tables instead of the current 3 – kranthi117 Dec 20 '14 at 16:10
  • I don't see why you would need 4 tables instead of 3. Regardless, you should probably mark this as the correct answer. – Alan Hay Dec 21 '14 at 09:25