Spring Data JPARepository: How to conditionally fetch children entites

前端 未结 5 1389
余生分开走
余生分开走 2020-12-08 14:28

How can one configure their JPA Entities to not fetch related entities unless a certain execution parameter is provided.

According to Spring\'s documentation, 4.3.9

5条回答
  •  青春惊慌失措
    2020-12-08 15:01

    Spring data does not ignore fetch=FetchType.Lazy.

    My problem was that I was using dozer-mapping to covert my entities to graphs. Evidently dozer calls the getters and setters to map two objects, so I needed to add a custom field mapper configuration to ignore PersistentCollections...

    GlobalCustomFieldMapper.java:

    public class GlobalCustomFieldMapper implements CustomFieldMapper 
    {
        public boolean mapField(Object source, Object destination, Object sourceFieldValue, ClassMap classMap, FieldMap fieldMapping) 
        {
           if (!(sourceFieldValue instanceof PersistentCollection)) {
                // Allow dozer to map as normal
                return;
            }
            if (((PersistentCollectiosourceFieldValue).wasInitialized()) {
                // Allow dozer to map as normal
                return false;
            }
    
            // Set destination to null, and tell dozer that the field is mapped
            destination = null;
            return true;
        }   
    }
    

提交回复
热议问题