简体   繁体   中英

How to explicitly load a LAZY fetching member of a hibernate Entity

Due to performance concern I have make most of the relation mapping in hibernate as fetch = fetchType.LAZY to avoid unnecessary query to the db.

....
private ConsumerEntity consumerEntity;

@ManyToOne(fetchType.LAZY)
@JoinColumn(name="orderId", insertable=false, updateable=false)
public ConsumerEntity getConsumerEntity(){
    return this.consumerEntity;
}
....

Above shows the mapping setting of relation for OrderEntity and ConsumerEntity .

Each time the callers do a query, I will open a session, process the query and return them the result, then close the session.

Public OrderEntity getOrderEntity(orderQueryParam){
   Sting hql = buildHqlStrFromParam(orderQueryParam);
   return (OrderEntity)this.getEntityByHql(hql); // in the method just 1. open a session; 2. retrieve entity 3. close the session;
}

But sometimes I know caller may need the related records as well. Like, if he ask about a specific Order record, I may want to give him the consumerEntity as well, so He can just do a dot thing to get the information he needed, and won't have to process a second query or get a lazy-loading-exception because the session has been closed:

  ...
  OrderEntity order = TradeService.getOrderEntity(orderQueryParam);
  ConsumerEntity consumer = order.getConsumerEntity();
  ....

But the scenario is very rare so that I don't want to change the fetchType to EAGER .

How to do this? I mean I want to have a choose whether or not loaded the ConsumerEntity which was configured as fetchType.LAZY .

Pass a boolean check to load the consumer entity if that flag is true than call getter method, It will load your lazy data into the object and will available further.

Public OrderEntity getOrderEntity(orderQueryParam, boolean loadConsumerEntity){
    Sting hql = buildHqlStrFromParam(orderQueryParam);
    OrderEntity entity = this.getEntityByHql(hql);
    if(loadConsumerEntity){
      // Your session shoud still open here
      entity.getConsumerEntity();
    }
    return entity; 
}

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