{"id":138225,"date":"2025-10-21T18:02:00","date_gmt":"2025-10-21T15:02:00","guid":{"rendered":"https:\/\/www.javacodegeeks.com\/?p=138225"},"modified":"2025-10-21T10:02:58","modified_gmt":"2025-10-21T07:02:58","slug":"preventing-jackson-from-fetching-lazy-entity-fields-example","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html","title":{"rendered":"Preventing Jackson from Fetching Lazy Entity Fields Example"},"content":{"rendered":"<h2 class=\"wp-block-heading\">1. Introduction<\/h2>\n<p>The Spring Boot JPA project uses Jackson for JSON serialization. When Jackson serializes a JPA entity, it can trigger lazy-loading of associated entities even outside of transactions. If the Hibernates proxies are closed, then accessing a lazy field throws <code>HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role<\/code>. In this example, I will demonstrate how it happened and three strategies to prevent Jackson fetching lazy fields.<\/p>\n<ul class=\"wp-block-list\">\n<li>Annotate with <code>@JsonIgnore<\/code> for the lazy-loading fields<\/li>\n<li>Use DTO Projection in the Rest controller<\/li>\n<li>Use DTO POJO in the Rest controller<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">2. Setup<\/h2>\n<h3 class=\"wp-block-heading\">2.1 Build.gradle<\/h3>\n<p>In this step, I will create a Gradle Java 21 project via Spring Initializer with: <a href=\"https:\/\/mvnrepository.com\/artifact\/org.mapstruct\/mapstruct\" target=\"_blank\" rel=\"noreferrer noopener\">MapStruct<\/a>, <a href=\"https:\/\/mvnrepository.com\/artifact\/org.springframework.data\/spring-data-jpa\" target=\"_blank\" rel=\"noreferrer noopener\">Spring Data JPA<\/a>, and <a href=\"https:\/\/mvnrepository.com\/artifact\/com.h2database\/h2\" target=\"_blank\" rel=\"noreferrer noopener\">H2<\/a> libraries.<\/p>\n<p><span style=\"text-decoration: underline\"><em>build.gradle<\/em><\/span><\/p>\n<pre class=\"brush:plain\">plugins {\n\tid 'java'\n\tid 'org.springframework.boot' version '3.5.6'\n\tid 'io.spring.dependency-management' version '1.1.7'\n}\n\ngroup = 'org.jcg.zheng.demo'\nversion = '0.0.1-SNAPSHOT'\ndescription = 'Demo project for Spring Boot'\n\njava {\n\ttoolchain {\n\t\tlanguageVersion = JavaLanguageVersion.of(21)\n\t}\n}\n\nconfigurations {\n\tcompileOnly {\n\t\textendsFrom annotationProcessor\n\t}\n}\n\nrepositories {\n\tmavenCentral()\n}\n\ndependencies {\n\timplementation 'org.springframework.boot:spring-boot-starter-data-jpa'\n\timplementation 'org.springframework.boot:spring-boot-starter-web'\n\t\/\/ https:\/\/mvnrepository.com\/artifact\/org.mapstruct\/mapstruct\n\timplementation 'org.mapstruct:mapstruct:1.6.3'\n\truntimeOnly 'com.h2database:h2'\t \n\tannotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3'\n\ttestImplementation 'org.springframework.boot:spring-boot-starter-test'\n\ttestRuntimeOnly 'org.junit.platform:junit-platform-launcher'\n}\n\ntasks.named('test') {\n\tuseJUnitPlatform()\n}\n<\/pre>\n<h3 class=\"wp-block-heading\">2.2 Application.properties<\/h3>\n<p>In this step, I will update the generated <code>application.properties<\/code> to enable the Hibernate logging and disable the Open Session In View(OSIV). <strong>Note<\/strong>: Spring Boot default OSIV to <code>true<\/code> &#8211; it forces persistence context to stay open so that the view layer can trigger the proxy initialization.<\/p>\n<p><span style=\"text-decoration: underline\"><em>application.properteis<\/em><\/span><\/p>\n<pre class=\"brush:plain\">spring.application.name=demolazyfetch\n\nlogging.level.org.springframework.web=DEBUG\nlogging.level.org.springframework.transaction.interceptor.TransactionInterceptor=DEBUG\n\nlogging.level.org.hibernate.SQL=DEBUG\n\nspring.jpa.show-sql=true\nspring.jpa.hibernate.ddl-auto=update\nspring.h2.console.enabled=true\n\n#default is true\nspring.jpa.open-in-view=false\n<\/pre>\n<h3 class=\"wp-block-heading\">2.3 DemolazyfetchApplication<\/h3>\n<p>In this step, I will show the generated <code>DemolazyfetchApplication.java<\/code>. No change is needed.<\/p>\n<p><span style=\"text-decoration: underline\"><em>DemolazyfetchApplication.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package org.jcg.zheng.demo.demolazyfetch;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class DemolazyfetchApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(DemolazyfetchApplication.class, args);\n\t}\n}\n<\/pre>\n<h3 class=\"wp-block-heading\"><a name=\"step24\"><\/a>2.4 Insert Test Data SQL<\/h3>\n<p>In this step, I will insert test data in the H2 database via H2 console.<\/p>\n<p><span style=\"text-decoration: underline\"><em>TestData.sql<\/em><\/span><\/p>\n<pre class=\"brush:sql\">insert into parent(id) values(1);\n\ninsert into child(id, price, quantity,parent_id) values(1,'10.5',2, 1);\ninsert into child(id, price, quantity,parent_id) values(2,'20.6',1, 1);\n<\/pre>\n<h2 class=\"wp-block-heading\">3. Parent &amp; Child Entity Classes<\/h2>\n<h3 class=\"wp-block-heading\"><a name=\"step31\"><\/a>3.1 Parent Entity<\/h3>\n<p>In this step, I will create a <code>Parent.java<\/code> entity class that annotates with <code>@OneToMany(mappedBy = \"parent\", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)<\/code> at the <code>List<\/code> of <code>Child<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Parent.java<\/em><\/span><\/p>\n<pre class=\"brush:java;highlight:[20,21]\">package org.jcg.zheng.demo.demolazyfetch.entity;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\n\nimport jakarta.persistence.CascadeType;\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.FetchType;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.OneToMany;\n\n@Entity\npublic class Parent {\n\t\n\t@Id\n\tprivate Long id;\n\t\n\/\/\t@JsonIgnore\n\t@OneToMany(mappedBy = \"parent\", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)\n\tprivate List&lt;Child&gt; children = new ArrayList&lt;&gt;();\n\t\n\tpublic List&lt;Child&gt; getChildren() {\n\t\treturn children;\n\t}\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setChildren(List&lt;Child&gt; children) {\n\t\tthis.children = children;\n\t}\n\t\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n}\n<\/pre>\n<ul class=\"wp-block-list\">\n<li>Line 20: commented <code>@JsonIgnore<\/code> initially till the <a href=\"#step85\">step 8.5<\/a>.<\/li>\n<li>Line 21: <code>@OneToMany(FetchType.<em>LAZY<\/em>)<\/code> for the <code>children<\/code>.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">3.2 Child Entity<\/h3>\n<p>In this step, I will create a <code>Child.java<\/code> entity class that annotates with <code>@ManyToOne<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Child.java<\/em><\/span><\/p>\n<pre class=\"brush:java;highlight:[20]\">package org.jcg.zheng.demo.demolazyfetch.entity;\n\nimport java.math.BigDecimal;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.FetchType;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.JoinColumn;\nimport jakarta.persistence.ManyToOne;\n\n@Entity\npublic class Child {\n\t@Id\n\tprivate Long id;\n\n\tprivate BigDecimal price;\n\n\tprivate int quantity;\n\n\t@ManyToOne(fetch=FetchType.LAZY)\n\t@JoinColumn(name = \"parent_id\")\n\tprivate Parent parent;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic Parent getParent() {\n\t\treturn parent;\n\t}\n\tpublic BigDecimal getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic int getQuantity() {\n\t\treturn quantity;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic void setParent(Parent parent) {\n\t\tparent.getChildren().add(this);\n\t\tthis.parent = parent;\n\t}\n\n\tpublic void setPrice(BigDecimal price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic void setQuantity(int quantity) {\n\t\tthis.quantity = quantity;\n\t}\n}\n<\/pre>\n<ul class=\"wp-block-list\">\n<li>Line 20: annotated <code>@ManyToOne(fetch=FetchType.<em>LAZY<\/em>)<\/code> for the <code>parent<\/code>.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">4. Parent &amp; Child DTO POJOs<\/h2>\n<h3 class=\"wp-block-heading\">4.1 ParentDto<\/h3>\n<p>In this step, I will create a <code>ParentDto.java<\/code> POJO class that implements <code>Serializable<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>ParentDto.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package org.jcg.zheng.demo.demolazyfetch.dto;\n\nimport java.io.Serializable;\nimport java.util.List;\n\n \npublic class ParentDto implements Serializable{\n \n\tprivate static final long serialVersionUID = -5451873400700416755L;\n\t\n\tprivate Long id;\n \n\tprivate List&lt;ChildDto&gt; orderItems;\n\t\n\tpublic ParentDto() {\n\t\tsuper();\n\t}\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic List&lt;ChildDto&gt; getOrderItems() {\n\t\treturn orderItems;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic void setOrderItems(List&lt;ChildDto&gt; orderItems) {\n\t\tthis.orderItems = orderItems;\n\t}\n\n}\n<\/pre>\n<h3 class=\"wp-block-heading\">4.2 ChildDto<\/h3>\n<p>In this step, I will create a <code>ChildDto.java<\/code> POJO class that implements <code>Serializable<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>ChildDto.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package org.jcg.zheng.demo.demolazyfetch.dto;\n\nimport java.io.Serializable;\nimport java.math.BigDecimal;\n\npublic class ChildDto implements Serializable {\n\n\tprivate static final long serialVersionUID = -3024223952933674948L;\n\n\tprivate Long id;\n\tprivate ParentDto order;\n\tprivate BigDecimal price;\n\tprivate int quantity;\n\n\tpublic ChildDto() {\n\t\tsuper();\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic ParentDto getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic BigDecimal getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic int getQuantity() {\n\t\treturn quantity;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic void setOrder(ParentDto order) {\n\t\tthis.order = order;\n\t}\n\n\tpublic void setPrice(BigDecimal price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic void setQuantity(int quantity) {\n\t\tthis.quantity = quantity;\n\t}\n\n}\n<\/pre>\n<h2 class=\"wp-block-heading\">5. Parent &amp; Child Repository Interfaces<\/h2>\n<h3 class=\"wp-block-heading\">5.1 Parent Repository<\/h3>\n<p>In this step, I will create a <code>ParentRepo.java<\/code> entity class that extends from <code>JpaRepository.<\/code><div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p><span style=\"text-decoration: underline\"><em>ParentRepo.java<\/em><\/span><\/p>\n<pre class=\"brush:java;highlight:[12]\">package org.jcg.zheng.demo.demolazyfetch.repo;\n\n\nimport java.util.List;\n\nimport org.jcg.zheng.demo.demolazyfetch.entity.Parent;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface ParentRepo extends JpaRepository&lt;Parent, Long&gt; {\n\tList&lt;ParentView&gt; findParentViewById(Long id);\n}\n<\/pre>\n<ul class=\"wp-block-list\">\n<li>Line 12: will be used at both <a href=\"#step72\">7.2<\/a> and <a href=\"#step84\">8.4<\/a> steps.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">5.2 Child Repository<\/h3>\n<p>In this step, I will create a <code>ChildRepo.java<\/code> entity class that extends with <code>JpaRepository<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Child.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package org.jcg.zheng.demo.demolazyfetch.repo;\n\nimport org.jcg.zheng.demo.demolazyfetch.entity.Child;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic interface ChildRepo extends JpaRepository&lt;Child, Long&gt; {\n\n}\n<\/pre>\n<h2 class=\"wp-block-heading\">6. Parent &amp; Child Mapper Interfaces<\/h2>\n<h3 class=\"wp-block-heading\">6.1 Parent Mapper<\/h3>\n<p>In this step, I will create a <code>ParentMapper.java<\/code> interface that converts the <code>Parent<\/code> entity to <code>ParentDto<\/code> POJO.<\/p>\n<p><span style=\"text-decoration: underline\"><em>ParentMapper.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package org.jcg.zheng.demo.demolazyfetch.mapper;\n\nimport org.jcg.zheng.demo.demolazyfetch.dto.ParentDto;\nimport org.jcg.zheng.demo.demolazyfetch.entity.Parent;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.factory.Mappers;\n\n@Mapper(componentModel = \"spring\")\npublic interface ParentMapper {\n\n\tParentMapper INSTANCE = Mappers.getMapper(ParentMapper.class);\n\n\tParentDto toDto(Parent order);\n}\n<\/pre>\n<h3 class=\"wp-block-heading\">6.2 Child Mapper<\/h3>\n<p>In this step, I will create a <code>ChildMapper.java<\/code> interface that converts the <code>Child<\/code> entity to <code>ChildDto<\/code> POJO..<\/p>\n<p><span style=\"text-decoration: underline\"><em>ChildMapper.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package org.jcg.zheng.demo.demolazyfetch.mapper;\n\nimport org.jcg.zheng.demo.demolazyfetch.dto.ChildDto;\nimport org.jcg.zheng.demo.demolazyfetch.entity.Child;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.factory.Mappers;\n\n@Mapper(componentModel = \"spring\")\npublic interface ChildMapper {\n\n\tChildMapper INSTANCE = Mappers.getMapper(ChildMapper.class);\n\n\tChildDto toDto(Child item);\n}\n<\/pre>\n<h2 class=\"wp-block-heading\">7. Rest Controller and Service<\/h2>\n<h3 class=\"wp-block-heading\">7.1 OrderService<\/h3>\n<p>In this step, I will create a <code>OrderService.java<\/code> entity class that has two methods: <code>ParentDto getDto(Long orderId)<\/code> and <code>ParentView getView(Long orderId)<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>OrderService.java<\/em><\/span><\/p>\n<pre class=\"brush:java;highlight:[37]\">package org.jcg.zheng.demo.demolazyfetch.service;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.jcg.zheng.demo.demolazyfetch.dto.ChildDto;\nimport org.jcg.zheng.demo.demolazyfetch.dto.ParentDto;\nimport org.jcg.zheng.demo.demolazyfetch.entity.Child;\nimport org.jcg.zheng.demo.demolazyfetch.entity.Parent;\nimport org.jcg.zheng.demo.demolazyfetch.mapper.ChildMapper;\nimport org.jcg.zheng.demo.demolazyfetch.mapper.ParentMapper;\nimport org.jcg.zheng.demo.demolazyfetch.repo.ParentRepo;\nimport org.jcg.zheng.demo.demolazyfetch.repo.ParentView;\nimport org.springframework.stereotype.Service;\n\nimport jakarta.transaction.Transactional;\n\n@Service\n@Transactional\npublic class OrderService {\n\tpublic OrderService(ParentRepo orderRepo, ParentMapper orderMapper, ChildMapper orderItemMapper) {\n\t\tsuper();\n\t\tthis.orderRepo = orderRepo;\n\t\tthis.orderMapper = orderMapper;\n\t\tthis.orderItemMapper = orderItemMapper;\n\t}\n\n\tprivate final ParentRepo orderRepo;\n\tprivate final ParentMapper orderMapper;\n\tprivate final ChildMapper orderItemMapper;\n\n\tpublic ParentDto getDto(Long orderId) {\n\t\tParentDto oDto = null;\n\t\tOptional&lt;Parent&gt; found = orderRepo.findById(orderId);\n\t\tif (found.isPresent()) {\n\t\t\tList&lt;Child&gt; items = found.get().getChildren();\n\t\t\toDto = orderMapper.toDto(found.get());\n\n\t\t\tList&lt;ChildDto&gt; iDs = new ArrayList&lt;&gt;();\n\t\t\toDto.setOrderItems(iDs);\n\t\t\tfor (Child oi : items) {\n\t\t\t\tiDs.add(orderItemMapper.toDto(oi));\n\t\t\t}\n\t\t}\n\n\t\treturn oDto;\n\t}\n\t\n\tpublic ParentView getView(Long orderId) {\n\t\treturn orderRepo.findParentViewById(orderId).get(0);\n\t}\n\n}\n<\/pre>\n<ul class=\"wp-block-list\">\n<li>Line 37: accessing lazy-loading fields within the transaction is ok.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\"><a name=\"step72\"><\/a>7.2 Parent View<\/h3>\n<p>In this step, I will create a <code>ParentView.java<\/code> interface that does not contain any lazy-loading fields.<\/p>\n<p><span style=\"text-decoration: underline\"><em>ParentView.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package org.jcg.zheng.demo.demolazyfetch.repo;\n\npublic interface ParentView {\t\n\tLong getId();\n}\n<\/pre>\n<h3 class=\"wp-block-heading\">7.3 DemoController<\/h3>\n<p>In this step, I will create a <code>DemoControlller.java<\/code> class that demonstrates xxx is thrown when calling <code>ResponseEntity getOrder(@PathVariable(\"id\") Long id)<\/code> .<\/p>\n<p><span style=\"text-decoration: underline\"><em>Child.java<\/em><\/span><\/p>\n<pre class=\"brush:java;highlight:[25]\">package org.jcg.zheng.demo.demolazyfetch.rest;\n\nimport java.util.Optional;\n\nimport org.jcg.zheng.demo.demolazyfetch.entity.Parent;\nimport org.jcg.zheng.demo.demolazyfetch.repo.ParentRepo;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\n@RequestMapping(\"\/demo\")\npublic class DemoController {\n\n\tpublic DemoController(ParentRepo parentRepo) {\n\t\tsuper();\n\t\tthis.parentRepo = parentRepo;\n\t}\n\n\tprivate final ParentRepo parentRepo;\n\n\t@GetMapping(\"{id}\")\n\tpublic ResponseEntity&lt;Parent&gt; getOrder(@PathVariable(\"id\") Long id) {\n\t\tOptional&lt;Parent&gt; found = parentRepo.findById(id);\n\t\tif (found.isPresent()) {\n\t\t\treturn ResponseEntity.ok(found.get());\n\t\t} else {\n\t\t\treturn ResponseEntity.notFound().build();\n\t\t}\n\t}\n}\n<\/pre>\n<ul class=\"wp-block-list\">\n<li>Line 25: The Rest response is the <code>Parent<\/code> Entity class.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">7.4 OrderController<\/h3>\n<p>In this step, I will create an <code>OrderControlller.java<\/code> class that demonstrates both DTO and view Interface addressed accessing the lazy-loading fields.<\/p>\n<p><span style=\"text-decoration: underline\"><em>title here<\/em><\/span><\/p>\n<pre class=\"brush:java;highlight:[24,33]\">package org.jcg.zheng.demo.demolazyfetch.rest;\n\nimport org.jcg.zheng.demo.demolazyfetch.dto.ParentDto;\nimport org.jcg.zheng.demo.demolazyfetch.repo.ParentView;\nimport org.jcg.zheng.demo.demolazyfetch.service.OrderService;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\n@RequestMapping(\"\/order\")\npublic class OrderController {\n\n\tpublic OrderController(OrderService orderService) {\n\t\tsuper();\n\t\tthis.orderService = orderService;\n\t}\n\n\tprivate final OrderService orderService;\n\n\t@GetMapping(\"\/dto\/{orderId}\")\n\tpublic ResponseEntity&lt;ParentDto&gt; getDto(@PathVariable(\"orderId\") Long orderId) {\n\t\tParentDto found = orderService.getDto(orderId);\n\t\tif (found == null) {\n\t\t\treturn ResponseEntity.notFound().build();\n\t\t}\n\t\treturn ResponseEntity.ok(found);\n\t}\n\n\t@GetMapping(\"\/view\/{orderId}\")\n\tpublic ResponseEntity&lt;ParentView&gt; getOrderP(@PathVariable(\"orderId\") Long orderId) {\n\t\tParentView found = orderService.getView(orderId);\n\t\treturn ResponseEntity.ok(found);\n\t}\n\n}\n<\/pre>\n<ul class=\"wp-block-list\">\n<li>Line 24: the Rest response is <code>ParentDto<\/code> POJO.<\/li>\n<li>Line 33: the Rest Response is <code>ParentView<\/code> Interface.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">8. Demonstrate<\/h2>\n<h3 class=\"wp-block-heading\">8.1 Start the Spring Boot Application<\/h3>\n<p>In this step, I will start the spring boot application and capture the server log.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Server Started Log<\/em><\/span><\/p>\n<pre class=\"brush:plain\">\n  .   ____          _            __ _ _\n \/\\\\ \/ ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\\/ _` | \\ \\ \\ \\\n \\\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )\n  '  |____| .__|_| |_|_| |_\\__, | \/ \/ \/ \/\n =========|_|==============|___\/=\/_\/_\/_\/\n\n :: Spring Boot ::                (v3.5.6)\n\n2025-10-12T14:17:58.348-05:00  INFO 22396 --- [demolazyfetch] [           main] o.j.z.d.d.DemolazyfetchApplication       : Starting DemolazyfetchApplication using Java 21.0.8 with PID 22396 (C:\\MaryZheng\\workspace\\demolazyfetch\\bin\\main started by zzhen in C:\\MaryZheng\\workspace\\demolazyfetch)\n2025-10-12T14:17:58.353-05:00  INFO 22396 --- [demolazyfetch] [           main] o.j.z.d.d.DemolazyfetchApplication       : No active profile set, falling back to 1 default profile: \"default\"\n2025-10-12T14:17:58.943-05:00  INFO 22396 --- [demolazyfetch] [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.\n2025-10-12T14:17:58.995-05:00  INFO 22396 --- [demolazyfetch] [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 38 ms. Found 2 JPA repository interfaces.\n2025-10-12T14:17:59.384-05:00  INFO 22396 --- [demolazyfetch] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)\n2025-10-12T14:17:59.393-05:00  INFO 22396 --- [demolazyfetch] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]\n2025-10-12T14:17:59.394-05:00  INFO 22396 --- [demolazyfetch] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat\/10.1.46]\n2025-10-12T14:17:59.434-05:00  INFO 22396 --- [demolazyfetch] [           main] o.a.c.c.C.[Tomcat].[localhost].[\/]       : Initializing Spring embedded WebApplicationContext\n2025-10-12T14:17:59.436-05:00  INFO 22396 --- [demolazyfetch] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1039 ms\n2025-10-12T14:17:59.633-05:00  INFO 22396 --- [demolazyfetch] [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]\n2025-10-12T14:17:59.692-05:00  INFO 22396 --- [demolazyfetch] [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 6.6.29.Final\n2025-10-12T14:17:59.724-05:00  INFO 22396 --- [demolazyfetch] [           main] o.h.c.internal.RegionFactoryInitiator    : HHH000026: Second-level cache disabled\n2025-10-12T14:17:59.950-05:00  INFO 22396 --- [demolazyfetch] [           main] o.s.o.j.p.SpringPersistenceUnitInfo      : No LoadTimeWeaver setup: ignoring JPA class transformer\n2025-10-12T14:17:59.973-05:00  INFO 22396 --- [demolazyfetch] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...\n2025-10-12T14:18:00.114-05:00  INFO 22396 --- [demolazyfetch] [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:9dfd436a-e6f6-47b3-8f35-ee35bcb3571b user=SA\n2025-10-12T14:18:00.115-05:00  INFO 22396 --- [demolazyfetch] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.\n2025-10-12T14:18:00.161-05:00  INFO 22396 --- [demolazyfetch] [           main] org.hibernate.orm.connections.pooling    : HHH10001005: Database info:\n\tDatabase JDBC URL [Connecting through datasource 'HikariDataSource (HikariPool-1)']\n\tDatabase driver: undefined\/unknown\n\tDatabase version: 2.3.232\n\tAutocommit mode: undefined\/unknown\n\tIsolation level: undefined\/unknown\n\tMinimum pool size: undefined\/unknown\n\tMaximum pool size: undefined\/unknown\n2025-10-12T14:18:00.654-05:00  INFO 22396 --- [demolazyfetch] [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000489: No JTA platform available (set 'hibernate.transaction.jta.platform' to enable JTA platform integration)\n2025-10-12T14:18:00.681-05:00 DEBUG 22396 --- [demolazyfetch] [           main] org.hibernate.SQL                        : create table child (id bigint not null, price numeric(38,2), quantity integer not null, parent_id bigint, primary key (id))\nHibernate: create table child (id bigint not null, price numeric(38,2), quantity integer not null, parent_id bigint, primary key (id))\n2025-10-12T14:18:00.685-05:00 DEBUG 22396 --- [demolazyfetch] [           main] org.hibernate.SQL                        : create table parent (id bigint not null, primary key (id))\nHibernate: create table parent (id bigint not null, primary key (id))\n2025-10-12T14:18:00.686-05:00 DEBUG 22396 --- [demolazyfetch] [           main] org.hibernate.SQL                        : alter table if exists child add constraint FK7dag1cncltpyhoc2mbwka356h foreign key (parent_id) references parent\nHibernate: alter table if exists child add constraint FK7dag1cncltpyhoc2mbwka356h foreign key (parent_id) references parent\n2025-10-12T14:18:00.692-05:00  INFO 22396 --- [demolazyfetch] [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'\n2025-10-12T14:18:01.213-05:00 DEBUG 22396 --- [demolazyfetch] [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : 5 mappings in 'requestMappingHandlerMapping'\n2025-10-12T14:18:01.287-05:00 DEBUG 22396 --- [demolazyfetch] [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [\/webjars\/**, \/**] in 'resourceHandlerMapping'\n2025-10-12T14:18:01.311-05:00 DEBUG 22396 --- [demolazyfetch] [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 @ModelAttribute, 0 @InitBinder, 1 RequestBodyAdvice, 1 ResponseBodyAdvice\n2025-10-12T14:18:01.356-05:00 DEBUG 22396 --- [demolazyfetch] [           main] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 @ExceptionHandler, 1 ResponseBodyAdvice\n2025-10-12T14:18:01.391-05:00  INFO 22396 --- [demolazyfetch] [           main] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '\/h2-console'. Database available at 'jdbc:h2:mem:9dfd436a-e6f6-47b3-8f35-ee35bcb3571b'\n2025-10-12T14:18:01.471-05:00  INFO 22396 --- [demolazyfetch] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '\/'\n2025-10-12T14:18:01.476-05:00  INFO 22396 --- [demolazyfetch] [           main] o.j.z.d.d.DemolazyfetchApplication       : Started DemolazyfetchApplication in 3.484 seconds (process running for 3.758)\n<\/pre>\n<p>Once the server is up, run the <code>TestData.sql<\/code> outlined at <a href=\"#step24\">step 2.4<\/a> to prepare the test data.<\/p>\n<h3 class=\"wp-block-heading\">8.2 Test DemoController for LazyInititionException<\/h3>\n<p>In this step, I will send Get <a href=\"http:\/\/localhost:8080\/demo\/1\" target=\"_blank\" rel=\"noreferrer noopener\">http:\/\/localhost:8080\/demo\/1<\/a> to capture the server log.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Server.log<\/em><\/span><\/p>\n<pre class=\"brush:plain;highlight:[6,7];wrap-lines:true\">2025-10-12T13:24:49.852-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : GET \"\/demo\/1\", parameters={}\n2025-10-12T13:24:49.853-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.jcg.zheng.demo.demolazyfetch.rest.DemoController#getOrder(Long)\n2025-10-12T13:24:49.854-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] org.hibernate.SQL                        : select p1_0.id from parent p1_0 where p1_0.id=?\nHibernate: select p1_0.id from parent p1_0 where p1_0.id=?\n2025-10-12T13:24:49.856-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application\/json', given [application\/json] and supported [application\/json, application\/*+json]\n2025-10-12T13:24:49.857-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [org.jcg.zheng.demo.demolazyfetch.entity.Parent@3ff5b054]\n2025-10-12T13:24:49.859-05:00  WARN 9384 --- [demolazyfetch] [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: org.jcg.zheng.demo.demolazyfetch.entity.Parent.children: could not initialize proxy - no Session]\n2025-10-12T13:24:49.860-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Completed 500 INTERNAL_SERVER_ERROR\n2025-10-12T13:24:49.860-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : \"ERROR\" dispatch for GET \"\/error\", parameters={}\n2025-10-12T13:24:49.860-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)\n2025-10-12T13:24:49.860-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Found 'Content-Type:application\/json' in response\n2025-10-12T13:24:49.861-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{timestamp=Sun Oct 12 13:24:49 CDT 2025, status=500, error=Internal Server Error, path=\/demo\/1}]\n2025-10-12T13:24:49.861-05:00 DEBUG 9384 --- [demolazyfetch] [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Exiting from \"ERROR\" dispatch, status 500\n<\/pre>\n<ul class=\"wp-block-list\">\n<li>Line 6: trying to write to <code>Parent<\/code> Entity class as the Rest response.<\/li>\n<li>Line 7: failed to write to JSON when accessing the <code>getChildren<\/code> as it is a lazy-loading field.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">8.3 Test OrderController for DTO<\/h3>\n<p>In this step, I will send GET <a href=\"http:\/\/localhost:8080\/order\/dto\/1\" target=\"_blank\" rel=\"noreferrer noopener\">http:\/\/localhost:8080\/order\/dto\/1<\/a> to capture the Rest response.<\/p>\n<p><span style=\"text-decoration: underline\"><em>http:\/\/localhost:8080\/order\/dto\/1 Response<\/em><\/span><\/p>\n<pre class=\"brush:plain\">{\n  \"id\": 1,\n  \"orderItems\": [\n    {\n      \"id\": 1,\n      \"order\": null,\n      \"price\": 10.50,\n      \"quantity\": 2\n    },\n    {\n      \"id\": 2,\n      \"order\": null,\n      \"price\": 20.60,\n      \"quantity\": 1\n    }\n  ]\n}<\/pre>\n<ul class=\"wp-block-list\">\n<li>DTO is returned in the Rest response &#8211; the lazy-loading field is accessed inside the <code>OrderService<\/code> and mapped to DTO via mapper.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\"><a name=\"step84\"><\/a>8.4 Test OrderController for ParentView Interface<\/h3>\n<p>In this step, I will send GET <a href=\"http:\/\/localhost:8080\/order\/view\/1\" target=\"_blank\" rel=\"noreferrer noopener\">http:\/\/localhost:8080\/order\/view\/1<\/a> and capture the Rest response.<\/p>\n<p><span style=\"text-decoration: underline\"><em>http:\/\/localhost:8080\/order\/view\/1 Response<\/em><\/span><\/p>\n<pre class=\"brush:plain\">{\n  \"id\": 1\n}<\/pre>\n<ul class=\"wp-block-list\">\n<li>The lazy-loaded fields are not included in the Rest response as the <code>ParentView<\/code> does not include it.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\"><a name=\"step85\"><\/a>8.5 Update Parent Entity with @JsonIgnore<\/h3>\n<p>In this step, I will uncomment the <code>@JsonIgnore<\/code> annotation in the <code>Parent.java<\/code> class defined at <a href=\"#step31\">step 3.1<\/a>. Restart the Spring Boot application and send GET <a href=\"http:\/\/localhost:8080\/demo\/1\" target=\"_blank\" rel=\"noreferrer noopener\">http:\/\/localhost:8080\/demo\/1<\/a> and capture the Rest response.<\/p>\n<p><span style=\"text-decoration: underline\"><em>http:\/\/localhost:8080\/demo\/1 Response<\/em><\/span><\/p>\n<pre class=\"brush:plain\">{\n  \"id\": 1\n}<\/pre>\n<ul class=\"wp-block-list\">\n<li>The lazy-loaded fields are not included in the Rest response as <code>@JsonIgnore<\/code> filtered it.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">9. Conclusion<\/h2>\n<p>In this example, I demonstrated three ways to prevent Jackson from accessing un-fetched entities when serializing lazy-loaded fields.<\/p>\n<ul class=\"wp-block-list\">\n<li>DTO POJO mapper &#8211; this is the cleanest solution, but requires extra mapping logic.<\/li>\n<li><code>@JsonIgnore<\/code> &#8211; this is simplest if lazy-loading fields are not needed.<\/li>\n<li>Hibernate projection interface &#8211; this is another simpler solution if lazy-loading fields are not needed.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">10. Download<\/h2>\n<p>This was an example of a Gradle project which handled lazy entity field serialization.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2025\/10\/demolazyfetch.zip\"><strong>Preventing Jackson from Fetching Lazy Entity Fields Example<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>1. Introduction The Spring Boot JPA project uses Jackson for JSON serialization. When Jackson serializes a JPA entity, it can trigger lazy-loading of associated entities even outside of transactions. If the Hibernates proxies are closed, then accessing a lazy field throws HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role. In &hellip;<\/p>\n","protected":false},"author":128892,"featured_media":175,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,6],"tags":[971,162,2871],"class_list":["post-138225","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-enterprise-java","category-java","tag-hibernate","tag-jackson","tag-lazy-loading"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Preventing Jackson from Fetching Lazy Entity Fields Example - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"Interested to learn more about lazy entity field serialization? Then check out our detailed examples!\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Preventing Jackson from Fetching Lazy Entity Fields Example - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"Interested to learn more about lazy entity field serialization? Then check out our detailed examples!\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2025-10-21T15:02:00+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/json-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Mary Zheng\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Mary Zheng\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html\"},\"author\":{\"name\":\"Mary Zheng\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/33e795ab61de7fab61ed89b4de1668f5\"},\"headline\":\"Preventing Jackson from Fetching Lazy Entity Fields Example\",\"datePublished\":\"2025-10-21T15:02:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html\"},\"wordCount\":798,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/json-logo.jpg\",\"keywords\":[\"Hibernate\",\"Jackson\",\"Lazy Loading\"],\"articleSection\":[\"Enterprise Java\",\"Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html\",\"name\":\"Preventing Jackson from Fetching Lazy Entity Fields Example - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/json-logo.jpg\",\"datePublished\":\"2025-10-21T15:02:00+00:00\",\"description\":\"Interested to learn more about lazy entity field serialization? Then check out our detailed examples!\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/json-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/json-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Preventing Jackson from Fetching Lazy Entity Fields Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/33e795ab61de7fab61ed89b4de1668f5\",\"name\":\"Mary Zheng\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2024\\\/04\\\/cropped-Mary-Zheng-96x96.jpg\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2024\\\/04\\\/cropped-Mary-Zheng-96x96.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2024\\\/04\\\/cropped-Mary-Zheng-96x96.jpg\",\"caption\":\"Mary Zheng\"},\"description\":\"Mary graduated from the Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She worked as a lead Software Engineer where she led and worked with others to design, implement, and monitor the software solution.\",\"sameAs\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/mary-zheng\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Preventing Jackson from Fetching Lazy Entity Fields Example - Java Code Geeks","description":"Interested to learn more about lazy entity field serialization? Then check out our detailed examples!","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html","og_locale":"en_US","og_type":"article","og_title":"Preventing Jackson from Fetching Lazy Entity Fields Example - Java Code Geeks","og_description":"Interested to learn more about lazy entity field serialization? Then check out our detailed examples!","og_url":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2025-10-21T15:02:00+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/json-logo.jpg","type":"image\/jpeg"}],"author":"Mary Zheng","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Mary Zheng","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html"},"author":{"name":"Mary Zheng","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/33e795ab61de7fab61ed89b4de1668f5"},"headline":"Preventing Jackson from Fetching Lazy Entity Fields Example","datePublished":"2025-10-21T15:02:00+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html"},"wordCount":798,"commentCount":0,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/json-logo.jpg","keywords":["Hibernate","Jackson","Lazy Loading"],"articleSection":["Enterprise Java","Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html","url":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html","name":"Preventing Jackson from Fetching Lazy Entity Fields Example - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/json-logo.jpg","datePublished":"2025-10-21T15:02:00+00:00","description":"Interested to learn more about lazy entity field serialization? Then check out our detailed examples!","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/json-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/json-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/preventing-jackson-from-fetching-lazy-entity-fields-example.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Preventing Jackson from Fetching Lazy Entity Fields Example"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/33e795ab61de7fab61ed89b4de1668f5","name":"Mary Zheng","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/04\/cropped-Mary-Zheng-96x96.jpg","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/04\/cropped-Mary-Zheng-96x96.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/04\/cropped-Mary-Zheng-96x96.jpg","caption":"Mary Zheng"},"description":"Mary graduated from the Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She worked as a lead Software Engineer where she led and worked with others to design, implement, and monitor the software solution.","sameAs":["https:\/\/www.javacodegeeks.com\/"],"url":"https:\/\/www.javacodegeeks.com\/author\/mary-zheng"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/138225","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/128892"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=138225"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/138225\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/175"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=138225"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=138225"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=138225"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}