简体   繁体   中英

Java Spring Hibernate, Runtime Optionally Perform Mappings?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM