Clear and flush

Let’s assume we have a root entity which has a child with a ManyToOne and that child has a ManyToMany with some other entity.

When I start a transaction I do the following steps in the same session.
I query data on that parent entity and so some deletion, updates and so forth.
I then immediatly do a select Jpa query with mutliple joins where I have some where clause on the collection of that ManyToMany.

My resultset contains elements in that ManyToMany that are outside the where clause I defined.
When I do a flush and clear before doing that select query it contains the actual data I wanted inside that where clause.

I assume this is because when I delete, update ad so forth the 1st level cache is updates and when I don the query it merges everything from the query + the 1st level cache therefore including results I don’t want.

Are my assumptions correct?

I’m not sure what you’re referring to with “My resultset contains elements”, are you talking about entities returned by the select query itself or the ones loaded in the @ManyToMany collection?

If the 1st level cache contains some entities they will still only be used for results that are actually returned by selection queries. On the other hand, if an entity which contains an associated collection is contained in the Persistence Context than that will of course be reused and the collection will not be automatically refreshed, so I guess this is your use-case.

If you want more help please share details about your entity mappings and the query you’re executing.

yes, the entity which contains an associated collection with entities that contain a property with date.
My select contains a where clause on that associated collection with date between.
When I do a flush and clear it contains only entities in that associated collection wich only have entities with that date.
If I don’t flush and clear it contains others also, probably because that associated collection is already in 1st level cache.
Just wanted to confirm that my assumption is correct.