1

I'm creating a RESTful web service. Everything works fine except when I add @JsonIgnore annotation in one of my classes that has a @OneToMany relationship. I am getting:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.packt.cardatabase.domain.Car["owner"]->com.packt.cardatabase.domain.Owner$HibernateProxy$AcLDWRSD["hibernateLazyInitializer"])

My pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.0</version>
    </dependency>
</dependencies>

My controller:

@RestController
public class CarController {
    @Autowired
    private CarRepository repository;

    @RequestMapping("/cars")
    public Iterable<Car> getCars(){
       return repository.findAll();
    }
}

My entity:

@Entity
@Table(name = "owner")
public class Owner {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long ownerid;
    private String firstname, lastname;
    @OneToMany(cascade =CascadeType.ALL, mappedBy="owner")

    @JsonIgnore <---- My problem
    private List<Car> cars;

    public Owner() {
    }
        ....
}

I can get the serialized data from the database when I remove @JsonIgnore. But not JSON format when I add the annotation.

lharry
  • 135
  • 1
  • 3
  • 16
  • Making a Java List (which is a generic interface) json ignorable is not straight forward as a regular object (String for example). you should ignore it differently since behind the scenes it is a JSON array. read the following: https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://stackoverflow.com/questions/15426232/dont-return-property-when-its-an-empty-list-with-jackson https://stackoverflow.com/questions/19894955/spring-jsonignore-not-working – Adi Ohana Apr 01 '19 at 15:12

1 Answers1

0

In your Car class, add this above your "Owner" declaration:

 @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
XavAleX
  • 1
  • 1