Lazy loading not working in JPA with hibernate












0















I am using JPA with hibernate in my spring boot application. Whenever I try to fetch the enities using jpa methods, its returning the entity plus all the association present inside it. I wanted to fetch the associated entities on demand(lazy loading), so I have provided fetch=FetchType.LAZY in my domain class. But still its returning all the entries.



Below is the code:
Case.java



    @Entity
@Table(name="smss_case")
public class Case implements Serializable {

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

@Id
@Column(name = "case_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer caseId;

@Column( name="case_title" )
private String caseTitle;

@JsonManagedReference
@OneToMany(mappedBy="smmsCase", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
private Set<Task> tasks;

}

}


Task.java



@Entity
@Table(name="task_prop")
public class Task implements Serializable {

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

@Id
@Column(name = "task_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer taskId;

@Column(name="task_title")
private String taskTitle;

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn( name="case_id", nullable=false)
private Case smmsCase;
// getters and setters
}


Service.java



public Case getCases(Integer id) {
return dao.findById(1).get();
}


Dao.java



public interface ServiceDao extends JpaRepository<Case, Integer>{

}


{

"caseId":1,
"caseTitle":"ergonomics",
"tasks":[

{

"taskId":1,
"taskTitle":"ca"
},
{

"taskId":2,
"taskTitle":"hazards"
},
{

"taskId":3,
"taskTitle":"remedy"
}
]
}



Any help will be highly appreciated!



Thanks!










share|improve this question

























  • What makes you think lazy loading doesn't work? My guess: you're serializing a Case to JSON, and you see its tasks in the JSON. Lazy loading doesn't mean "no loading". It means that when something (like the JSON serializer) calls a method of the set of tasks (to serialize them), then, and only then, JPA executes the query to load the tasks. Lazy loading is working fine. You just don"t understand what it means. Setting fetch=LAZY on a OneToMany is useless, BTW, since that's the default value.

    – JB Nizet
    Nov 25 '18 at 8:29













  • @ JB Nizet, Thanks for your response. I still have a confusion. No where in my service I am calling any methods of set of tasks. Still the getCases() method inside my Service is loading all the associated tasks. Please let me know whats going wrong here. Thanks!

    – grav
    Nov 25 '18 at 9:34











  • "when something (like the JSON serializer) calls a method of the set of tasks (to serialize them)". JSON serialization doesn't happen by magic. The JSON serializer goes through all the properties of your object to get their value and transform them to JSON. If they're a collection (like your set of tasks), it iterates through the collection, using their iterator() method. So that triggers the lazy loading.

    – JB Nizet
    Nov 25 '18 at 9:37











  • Can you share your controller code? Do you return your entity directly or some dto which represents it? It might be happened because of you return entity itself and the serializer calls related models while serialization.

    – Emre Savcı
    Nov 25 '18 at 9:43











  • @ JB Nizet, thank you so much!! You were right. Lazy loading is actually working but when I try to return the object from my API, it was calling the associated entities. @ Emre Savcı, Thanks for your response, I got it working. As mentioned, when the controller is returning the entity, object to json serialization is triggering the associations. To do this, I have configured MappingJackson2HttpMessageConverter. (reference: stackoverflow.com/questions/21708339/…)

    – grav
    Nov 25 '18 at 12:54
















0















I am using JPA with hibernate in my spring boot application. Whenever I try to fetch the enities using jpa methods, its returning the entity plus all the association present inside it. I wanted to fetch the associated entities on demand(lazy loading), so I have provided fetch=FetchType.LAZY in my domain class. But still its returning all the entries.



Below is the code:
Case.java



    @Entity
@Table(name="smss_case")
public class Case implements Serializable {

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

@Id
@Column(name = "case_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer caseId;

@Column( name="case_title" )
private String caseTitle;

@JsonManagedReference
@OneToMany(mappedBy="smmsCase", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
private Set<Task> tasks;

}

}


Task.java



@Entity
@Table(name="task_prop")
public class Task implements Serializable {

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

@Id
@Column(name = "task_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer taskId;

@Column(name="task_title")
private String taskTitle;

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn( name="case_id", nullable=false)
private Case smmsCase;
// getters and setters
}


Service.java



public Case getCases(Integer id) {
return dao.findById(1).get();
}


Dao.java



public interface ServiceDao extends JpaRepository<Case, Integer>{

}


{

"caseId":1,
"caseTitle":"ergonomics",
"tasks":[

{

"taskId":1,
"taskTitle":"ca"
},
{

"taskId":2,
"taskTitle":"hazards"
},
{

"taskId":3,
"taskTitle":"remedy"
}
]
}



Any help will be highly appreciated!



Thanks!










share|improve this question

























  • What makes you think lazy loading doesn't work? My guess: you're serializing a Case to JSON, and you see its tasks in the JSON. Lazy loading doesn't mean "no loading". It means that when something (like the JSON serializer) calls a method of the set of tasks (to serialize them), then, and only then, JPA executes the query to load the tasks. Lazy loading is working fine. You just don"t understand what it means. Setting fetch=LAZY on a OneToMany is useless, BTW, since that's the default value.

    – JB Nizet
    Nov 25 '18 at 8:29













  • @ JB Nizet, Thanks for your response. I still have a confusion. No where in my service I am calling any methods of set of tasks. Still the getCases() method inside my Service is loading all the associated tasks. Please let me know whats going wrong here. Thanks!

    – grav
    Nov 25 '18 at 9:34











  • "when something (like the JSON serializer) calls a method of the set of tasks (to serialize them)". JSON serialization doesn't happen by magic. The JSON serializer goes through all the properties of your object to get their value and transform them to JSON. If they're a collection (like your set of tasks), it iterates through the collection, using their iterator() method. So that triggers the lazy loading.

    – JB Nizet
    Nov 25 '18 at 9:37











  • Can you share your controller code? Do you return your entity directly or some dto which represents it? It might be happened because of you return entity itself and the serializer calls related models while serialization.

    – Emre Savcı
    Nov 25 '18 at 9:43











  • @ JB Nizet, thank you so much!! You were right. Lazy loading is actually working but when I try to return the object from my API, it was calling the associated entities. @ Emre Savcı, Thanks for your response, I got it working. As mentioned, when the controller is returning the entity, object to json serialization is triggering the associations. To do this, I have configured MappingJackson2HttpMessageConverter. (reference: stackoverflow.com/questions/21708339/…)

    – grav
    Nov 25 '18 at 12:54














0












0








0








I am using JPA with hibernate in my spring boot application. Whenever I try to fetch the enities using jpa methods, its returning the entity plus all the association present inside it. I wanted to fetch the associated entities on demand(lazy loading), so I have provided fetch=FetchType.LAZY in my domain class. But still its returning all the entries.



Below is the code:
Case.java



    @Entity
@Table(name="smss_case")
public class Case implements Serializable {

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

@Id
@Column(name = "case_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer caseId;

@Column( name="case_title" )
private String caseTitle;

@JsonManagedReference
@OneToMany(mappedBy="smmsCase", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
private Set<Task> tasks;

}

}


Task.java



@Entity
@Table(name="task_prop")
public class Task implements Serializable {

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

@Id
@Column(name = "task_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer taskId;

@Column(name="task_title")
private String taskTitle;

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn( name="case_id", nullable=false)
private Case smmsCase;
// getters and setters
}


Service.java



public Case getCases(Integer id) {
return dao.findById(1).get();
}


Dao.java



public interface ServiceDao extends JpaRepository<Case, Integer>{

}


{

"caseId":1,
"caseTitle":"ergonomics",
"tasks":[

{

"taskId":1,
"taskTitle":"ca"
},
{

"taskId":2,
"taskTitle":"hazards"
},
{

"taskId":3,
"taskTitle":"remedy"
}
]
}



Any help will be highly appreciated!



Thanks!










share|improve this question
















I am using JPA with hibernate in my spring boot application. Whenever I try to fetch the enities using jpa methods, its returning the entity plus all the association present inside it. I wanted to fetch the associated entities on demand(lazy loading), so I have provided fetch=FetchType.LAZY in my domain class. But still its returning all the entries.



Below is the code:
Case.java



    @Entity
@Table(name="smss_case")
public class Case implements Serializable {

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

@Id
@Column(name = "case_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer caseId;

@Column( name="case_title" )
private String caseTitle;

@JsonManagedReference
@OneToMany(mappedBy="smmsCase", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
private Set<Task> tasks;

}

}


Task.java



@Entity
@Table(name="task_prop")
public class Task implements Serializable {

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

@Id
@Column(name = "task_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer taskId;

@Column(name="task_title")
private String taskTitle;

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn( name="case_id", nullable=false)
private Case smmsCase;
// getters and setters
}


Service.java



public Case getCases(Integer id) {
return dao.findById(1).get();
}


Dao.java



public interface ServiceDao extends JpaRepository<Case, Integer>{

}


{

"caseId":1,
"caseTitle":"ergonomics",
"tasks":[

{

"taskId":1,
"taskTitle":"ca"
},
{

"taskId":2,
"taskTitle":"hazards"
},
{

"taskId":3,
"taskTitle":"remedy"
}
]
}



Any help will be highly appreciated!



Thanks!







hibernate jpa spring-data-jpa lazy-loading






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 9:38







grav

















asked Nov 25 '18 at 8:24









gravgrav

13




13













  • What makes you think lazy loading doesn't work? My guess: you're serializing a Case to JSON, and you see its tasks in the JSON. Lazy loading doesn't mean "no loading". It means that when something (like the JSON serializer) calls a method of the set of tasks (to serialize them), then, and only then, JPA executes the query to load the tasks. Lazy loading is working fine. You just don"t understand what it means. Setting fetch=LAZY on a OneToMany is useless, BTW, since that's the default value.

    – JB Nizet
    Nov 25 '18 at 8:29













  • @ JB Nizet, Thanks for your response. I still have a confusion. No where in my service I am calling any methods of set of tasks. Still the getCases() method inside my Service is loading all the associated tasks. Please let me know whats going wrong here. Thanks!

    – grav
    Nov 25 '18 at 9:34











  • "when something (like the JSON serializer) calls a method of the set of tasks (to serialize them)". JSON serialization doesn't happen by magic. The JSON serializer goes through all the properties of your object to get their value and transform them to JSON. If they're a collection (like your set of tasks), it iterates through the collection, using their iterator() method. So that triggers the lazy loading.

    – JB Nizet
    Nov 25 '18 at 9:37











  • Can you share your controller code? Do you return your entity directly or some dto which represents it? It might be happened because of you return entity itself and the serializer calls related models while serialization.

    – Emre Savcı
    Nov 25 '18 at 9:43











  • @ JB Nizet, thank you so much!! You were right. Lazy loading is actually working but when I try to return the object from my API, it was calling the associated entities. @ Emre Savcı, Thanks for your response, I got it working. As mentioned, when the controller is returning the entity, object to json serialization is triggering the associations. To do this, I have configured MappingJackson2HttpMessageConverter. (reference: stackoverflow.com/questions/21708339/…)

    – grav
    Nov 25 '18 at 12:54



















  • What makes you think lazy loading doesn't work? My guess: you're serializing a Case to JSON, and you see its tasks in the JSON. Lazy loading doesn't mean "no loading". It means that when something (like the JSON serializer) calls a method of the set of tasks (to serialize them), then, and only then, JPA executes the query to load the tasks. Lazy loading is working fine. You just don"t understand what it means. Setting fetch=LAZY on a OneToMany is useless, BTW, since that's the default value.

    – JB Nizet
    Nov 25 '18 at 8:29













  • @ JB Nizet, Thanks for your response. I still have a confusion. No where in my service I am calling any methods of set of tasks. Still the getCases() method inside my Service is loading all the associated tasks. Please let me know whats going wrong here. Thanks!

    – grav
    Nov 25 '18 at 9:34











  • "when something (like the JSON serializer) calls a method of the set of tasks (to serialize them)". JSON serialization doesn't happen by magic. The JSON serializer goes through all the properties of your object to get their value and transform them to JSON. If they're a collection (like your set of tasks), it iterates through the collection, using their iterator() method. So that triggers the lazy loading.

    – JB Nizet
    Nov 25 '18 at 9:37











  • Can you share your controller code? Do you return your entity directly or some dto which represents it? It might be happened because of you return entity itself and the serializer calls related models while serialization.

    – Emre Savcı
    Nov 25 '18 at 9:43











  • @ JB Nizet, thank you so much!! You were right. Lazy loading is actually working but when I try to return the object from my API, it was calling the associated entities. @ Emre Savcı, Thanks for your response, I got it working. As mentioned, when the controller is returning the entity, object to json serialization is triggering the associations. To do this, I have configured MappingJackson2HttpMessageConverter. (reference: stackoverflow.com/questions/21708339/…)

    – grav
    Nov 25 '18 at 12:54

















What makes you think lazy loading doesn't work? My guess: you're serializing a Case to JSON, and you see its tasks in the JSON. Lazy loading doesn't mean "no loading". It means that when something (like the JSON serializer) calls a method of the set of tasks (to serialize them), then, and only then, JPA executes the query to load the tasks. Lazy loading is working fine. You just don"t understand what it means. Setting fetch=LAZY on a OneToMany is useless, BTW, since that's the default value.

– JB Nizet
Nov 25 '18 at 8:29







What makes you think lazy loading doesn't work? My guess: you're serializing a Case to JSON, and you see its tasks in the JSON. Lazy loading doesn't mean "no loading". It means that when something (like the JSON serializer) calls a method of the set of tasks (to serialize them), then, and only then, JPA executes the query to load the tasks. Lazy loading is working fine. You just don"t understand what it means. Setting fetch=LAZY on a OneToMany is useless, BTW, since that's the default value.

– JB Nizet
Nov 25 '18 at 8:29















@ JB Nizet, Thanks for your response. I still have a confusion. No where in my service I am calling any methods of set of tasks. Still the getCases() method inside my Service is loading all the associated tasks. Please let me know whats going wrong here. Thanks!

– grav
Nov 25 '18 at 9:34





@ JB Nizet, Thanks for your response. I still have a confusion. No where in my service I am calling any methods of set of tasks. Still the getCases() method inside my Service is loading all the associated tasks. Please let me know whats going wrong here. Thanks!

– grav
Nov 25 '18 at 9:34













"when something (like the JSON serializer) calls a method of the set of tasks (to serialize them)". JSON serialization doesn't happen by magic. The JSON serializer goes through all the properties of your object to get their value and transform them to JSON. If they're a collection (like your set of tasks), it iterates through the collection, using their iterator() method. So that triggers the lazy loading.

– JB Nizet
Nov 25 '18 at 9:37





"when something (like the JSON serializer) calls a method of the set of tasks (to serialize them)". JSON serialization doesn't happen by magic. The JSON serializer goes through all the properties of your object to get their value and transform them to JSON. If they're a collection (like your set of tasks), it iterates through the collection, using their iterator() method. So that triggers the lazy loading.

– JB Nizet
Nov 25 '18 at 9:37













Can you share your controller code? Do you return your entity directly or some dto which represents it? It might be happened because of you return entity itself and the serializer calls related models while serialization.

– Emre Savcı
Nov 25 '18 at 9:43





Can you share your controller code? Do you return your entity directly or some dto which represents it? It might be happened because of you return entity itself and the serializer calls related models while serialization.

– Emre Savcı
Nov 25 '18 at 9:43













@ JB Nizet, thank you so much!! You were right. Lazy loading is actually working but when I try to return the object from my API, it was calling the associated entities. @ Emre Savcı, Thanks for your response, I got it working. As mentioned, when the controller is returning the entity, object to json serialization is triggering the associations. To do this, I have configured MappingJackson2HttpMessageConverter. (reference: stackoverflow.com/questions/21708339/…)

– grav
Nov 25 '18 at 12:54





@ JB Nizet, thank you so much!! You were right. Lazy loading is actually working but when I try to return the object from my API, it was calling the associated entities. @ Emre Savcı, Thanks for your response, I got it working. As mentioned, when the controller is returning the entity, object to json serialization is triggering the associations. To do this, I have configured MappingJackson2HttpMessageConverter. (reference: stackoverflow.com/questions/21708339/…)

– grav
Nov 25 '18 at 12:54












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465814%2flazy-loading-not-working-in-jpa-with-hibernate%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465814%2flazy-loading-not-working-in-jpa-with-hibernate%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Create new schema in PostgreSQL using DBeaver

Deepest pit of an array with Javascript: test on Codility

Costa Masnaga