Spring JPA Repository ignoring FetchType.LAZY

2019-08-10 03:36发布

问题:

I have my entity classes with OneToMany mappings defined and Spring JPA repository interfaces created by extending JpaRepository interface of spring.

I have set fetch as FetchType.LAZY explicitly on the associations in OneToMany annotation.

The problem I'm facing is that when I get a particular record using the repository, Spring is fetching the associated entity objects which are defined using OneToMany annotation and their subsequent associated entity objects and so on ignoring their fetch type.I am receiving huge amount of data to the web page when use it in a Spring REST Controller. Few times, it is also resulting in a StackOverflow exception when it encounters circular bindings.

I came across the following post on stackoverflow.com but the answer didn't seem to be relevant to the current situation..

Spring JPA loads all associated properties despite marking them as FetchType.LAZY in entity class

Update

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractEntity implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -2700585394392789902L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @CreatedDate
    private Date createdDate = new Date();

    @LastModifiedDate
    private Date lastModifiedDate = new Date();

    @CreatedBy
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn
    private User createdBy;

    @LastModifiedBy
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn
    private User lastModifiedBy;

    @javax.persistence.Version
    private long version;

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public Date getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(Date lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }

    @JsonIgnore
    public User getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(User createdBy) {
        this.createdBy = createdBy;
    }

    public void setLastModifiedBy(User lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }

    public long getVersion() {
        return version;
    }

    public void setVersion(long version) {
        this.version = version;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

}



@Entity
@Table(name = "currencies")
public class Currency extends AbstractMasterEntity {

    private static final long serialVersionUID = 1L;

    @Override
    public String toString() {
        return "Currency [code=" + code + ", name=" + name + "]";
    }
}