1

I am using spring data with hibernate to implement my backend and I found one (in my opinion) crazy thing.

See the following:

My data model:

FeedbackAction

 @Entity
 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
 @DiscriminatorColumn(name = "ACTIVITY_TYPE")
 @Where(clause = "is_deleted=0")
 public abstract class FeedbackAction {
      //...
      @ManyToOne
      @NotFound(action = NotFoundAction.IGNORE)
      private ShoppingItem shoppingItem;
      //...
 }

ShoppingItem

@Entity
@Where(clause = "is_deleted=0")
public class ShoppingItem {
    //...
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "shoppingItem")
    private List<FeedbackAction> feedbackActions;
    //...
}

Then I have a simple method in my repository layer.

@Override
public Page<K> findByShoppingItem(ShoppingItem shoppingItem, Pageable pageable);

The invocation of the above method results in the following queries (the comment is a subclass of feedback action):

Hibernate: select count(comment0_.id) as col_0_0_ from feedback_action comment0_ ...
Hibernate: select comment0_.id as id2_1_, ... from feedback_action ...
Hibernate: select user0_.id as id1_5_0_, ... from user user0_ ...
Hibernate: select shoppingit0_.id as id1_3_0_, ... from shopping_item ...

Now the crazy thing is that ShoppingItem (which I sent to the repository method as a parameter) is queried again, although I retrieved the ShoppingItem entity using

ShoppingItem shoppingItem = shoppingItemService.get(shoppingItemID);

right before calling the

repository.findByShoppingItem(shoppingItem, pageable)

Why is that so? Is there some annotation, or similar to avoid the duplicate querying?

There are maybe some possibilities to overcome this problem by retrieving the ShoppingItem entity by its id and then calling the .getFeedbackActions() on it, which fetches the feedback actions, but I am not sure how to use paging in this case.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
FilipR
  • 1,218
  • 4
  • 22
  • 39
  • 3
    Is the first query being executed in the same Hibernate session? If not, Hibernate won't keep it in the [first level caching](http://stackoverflow.com/a/337099/1199132) (default caching) and consequently, will have to execute the query again. – Aritz Feb 15 '16 at 07:13
  • Thank for your explanation. They were not executed in the same session. Annotating the service method with `@Transactional(propagation = Propagation.REQUIRED, readOnly = true)`eliminates selecting the known shopping item again. – FilipR Feb 15 '16 at 12:02

0 Answers0