0

In my database I have an Email Campaign that has 1 to many List, List has many to many Subscribers.

The problem I'm having is, for example, when I pull a campaign I don't always want all the subscribers (could be a lot of subscribers and only wanting to see the different campaigns).

When creating mapping is there a way to optionally do the mappings (at runtime decide)? Or what is the solution to the problem? Should I just pull everything from database and output the portion requested? Seems like a lot of overhead.

4

1 回答 1

1

I am going to assume you have some mappings similar to the following based on how you described your data model (note I am leaving the fetch type as the default of LAZY).

@Entity
public class Campaign {
  // ...
  @OneToMany
  private List<MailingList> lists;
}

@Entity
public class MailingList {
  // ...
  @ManyToMany
  private List<Subscriber> subscribers;
}

@Entity
public class Subscriber {
  // ...
}

If you want to fetch the Campaign entities and the associated MailingList relationships, you can easily do that in HQL/JPQL as follows:

FROM Campaign c JOIN FETCH c.lists

That will not fetch the subscriber list because a @ManyToMany association is by default lazy and thus is only going to be fetched if and only if you were to call getSubscribers().

You should always favor LAZY fetching in your mappings and then specify the appropriate join fetches at query-time, allowing for the most granular control.

于 2017-02-28T05:13:02.630 回答