Lazy Initialized object load without fetch with hi

2019-08-24 03:08发布

问题:

SchoolDto:

    @Id
    @Column(name = "c_sm_npk_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "school_sequence")
    @SequenceGenerator(name = "school_sequence", sequenceName = "t_school_master_c_sm_npk_id_seq", initialValue = 1, allocationSize = 1)
    private Long id;
    @Column(name="c_sm_vnm_name")
    private String name;
    @ManyToOne(cascade = {CascadeType.MERGE},fetch=FetchType.LAZY)
    UserDto owner;

   /*Many other fileds omit for simplicity with getter/setter methods*/

UserDto

public class UserDto implements Serializable {
    private static final long serialVersionUID = 1L;

    public UserDto() {
    }

    @Id
    @Column(name = "c_um_npk_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_sequence")
    @SequenceGenerator(name = "user_sequence", sequenceName = "t_user_master_c_um_npk_id_seq", initialValue = 1, allocationSize = 1)
    private Long id;
    @Column(name = "c_um_vnm_username", nullable = false)
    private String username;
    @Column(name = "c_um_vnm_email_address")
    private String emailId;
    @JsonSerialize(using = JsonDateSerializer.class)
    @Column(name = "c_um_dnm_birth_date",nullable=false)
    @Temporal(TemporalType.DATE)
    private Date birthdate;
    @Column(name="c_um_nnm_age",nullable=false)

    private int age;
    @Column(name = "c_um_vnm_first_name")
    private String firstName;
    @Column(name = "c_um_vnm_last_name")
    private String lastName;
    @Column(name = "c_um_vnm_mobile_number")
    private String mobileNumber;
    @Column(name = "c_um_vnm_gender")
    private String gender;
    @JsonManagedReference("user-role")
    @OneToMany(mappedBy = "userDto", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<RoleDto> roleDtos;
 /* getter setter of properties */
}

Here, I have defined owner as Lazy collection. but when I try to find all schools as below:

public List<SchoolDto> getAllSchoolsWithAdvanceSearch(SchoolSearchDto schoolSearchDto) {
        return getEntityManager().createQuery("SELECT s from SchoolDto s").setFirstResult(schoolSearchDto.getFrom()).setMaxResults(schoolSearchDto.getSize()).getResultList();
    }

this return list of schools, with all its owner info including roles of the owner (which is again Lazy collection form UserDto) , when I log the hibernate query,I get only one select as below:

select
        schooldto0_.c_sm_npk_id as c1_24_,
        schooldto0_.c_sm_vnm_address_line_1 as c2_24_,
        schooldto0_.owner_c_um_npk_id as owner17_24_
    from
        t_school_master schooldto0_

during search, I come across that it may be Jackson serialization issue, so I did below changes as per jackson - do not serialize lazy objects & Avoid Jackson serialization on non fetched lazy objects as below

application-servlet.xml

    <mvc:annotation-driven>
        <mvc:message-converters>
            <ref bean="jsonHttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>


       <bean id="jsonHttpMessageConverter"  class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.util.HibernateAwareObjectMapper" />
                </property>
            </bean>

HibernateAwareObjectMapper.java

public HibernateAwareObjectMapper() {
        this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        Hibernate4Module module = new Hibernate4Module();
        module.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, false);
        module.disable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION);
        registerModule(module);
    }

Note : I need owner detail later, so I can not mark it as @JsonIgnore.

Please help me to solve this issue. Thanks in advance

Edit : current output

0:  {
       "id": 1
       "name": "school1"
       "address1": null
       owner : {
           "id" : 1,
           "firstName": "Rutesha",
           "lastName" : "Patel",
           "roles":[{
                "name" : "SCHOOL_ADMIN"
            }]
       }
}

Edit : Expected output

0:  {
       "id": 1
       "name": "school1"
       "address1": null
}

OR 

0:  {
       "id": 1
       "name": "school1"
       "address1": null
       owner : null
}

回答1:

Do the following changes

return getEntityManager().createQuery("SELECT s.id,s.name,s.address1 from SchoolDto s").setFirstResult(schoolSearchDto.getFrom()).setMaxResults(schoolSearchDto.getS‌​ize()).getResultList(); 

@ManyToOne - like annotations have according to the documentation the same problem, but in that case it much more likely that the JPA provider will consider the FetchType hint.

@ManyToOne(cascade={CascadeType.MERGE},optional = false,fetch=FetchType.LAZY )
UserDto owner;

Also following annotations can help.

@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner")
@Cascade(CascadeType.ALL)
@Fetch(FetchMode.SELECT)
@BatchSize(size = 10)

Possibly @JoinColumn(name="other_entity_fk") should be used.

For Example

@ManyToOne(fetch = FetchType.LAZY)
@Fetch(FetchMode.SUBSELECT)
@JoinColumn(name = "STOCK_ID", nullable = false)
public Stock getStock() {
    return this.stock;
}

Reference Strategies for Fetch mode