简体   繁体   中英

@JsonBackreference is ignored when using excerptProjection

In my Spring Data Rest Application a @JsonBackReference is ignored when a excerptProjection is defined.

When calling GET /foos/{id} I get as response: ( _link elements are omitted here)

{
  "text": "Foo",
  "additionalText": "Additional Text",
  "bar": {
    "text": "Bar",
    "_embedded": {
      "foo": {
        "text": "Foo",
        "bar": {
          "text": "Bar"
        }
      }
    }
  }
}

Given:

@Entity
public class Foo {

    @Id
    @GeneratedValue
    private Long id;

    private String text;

    private String additionalText;

    @JsonManagedReference
    @OneToOne(mappedBy = "foo", cascade = ALL)
    private Bar bar;
}

and

@Entity
public class Bar {

    @Id
    @GeneratedValue
    private Long id;

    private String text;

    @JsonBackReference
    @OneToOne
    private Foo foo;
}

with a Repository:

@RepositoryRestResource(excerptProjection = FooPublicProjection.class)
public interface FooRepository extends CrudRepository<Foo, Long> {}

If I remove the excerptProjection definition, I get the following result:

{
  "text": "Foo",
  "additionalText": "Additional Text",
  "bar": {
    "text": "Bar"
  }
}

What can I do to let Spring Data Rest not render the Foo within its own child node?

This is a solution providing you're using Jackson (which I guess you do). In my project, I used JSOG to handle all my cyclic relations. I think it can solve the issue in your case as well.

@Entity
@JsonIdentityInfo(generator = JSOGGenerator.class)
public class Foo {

    @Id
    @GeneratedValue
    private Long id;

    private String text;

    private String additionalText;

    @JsonManagedReference
    @OneToOne(mappedBy = "foo", cascade = ALL)
    private Bar bar;
}

and:

@Entity
@JsonIdentityInfo(generator = JSOGGenerator.class)
public class Bar {

    @Id
    @GeneratedValue
    private Long id;

    private String text;

    @JsonBackReference
    @OneToOne
    private Foo foo;
}

Notice that if your client is javascript, there's a complementing JSOG lib that can parse your JSON and resolve cycles automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM