Spring Data Rest post fails to save nested object

Paolo :

I have these Objects:

@Data
@Entity
@Table
@EqualsAndHashCode(callSuper = true)
public class User extends AbstractEntity implements Serializable {

   private static final long serialVersionUID = -55089179131569489L;

   private String username;
   private String email;
   private boolean admin;
   private String name;
   private String surname;

   @OneToMany(mappedBy = "owner")
   private List<Ad> ads;
}

and

@Entity
@Table
@Data
@EqualsAndHashCode(callSuper = true)
public class Ad extends AbstractEntity implements Serializable {

    private static final long serialVersionUID = -4590938091334150254L;
    private String name;
    private String description;
    private double price;

    @Enumerated(EnumType.STRING)
    private Category category;

    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "OWNER_ID")
    private User owner;

}

When I try to execute a POST with an object of type Ad.class with inside an existing object of type User.class (already in the Database) the service saves only the Ad object and the join column "OWNER_ID" remains empty.

I think that the mapping is correct. Could you help me to figure out the problem?

This is my Repository:

@Repository
@Transactional(readOnly = true)
public interface AdRepository extends PagingAndSortingRepository<Ad, String> 
{}  

and this is my RestRepository

@RepositoryRestResource(collectionResourceRel = "ad", path = "ad")
public interface AdRestRepository extends PagingAndSortingRepository<Ad, String> {}
Supun Wijerathne :

If I step back a little and generalize your problem,

You are trying to POST a sub resource and expect both actions of

  • making a new resource (Ad)
  • making association with the owner (User)

to be happened with a single call.

But unfortunately spring-data-rest does not support such a behavior. You need 2 calls to do this.

  • One to make the resource (Ad) => POST to /ads with actual payload
  • Second to make the association => POST to users/{ownerId} with the hateoas link of the resource created by the first call.

Take a look at this section of official documentation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108036&siteId=1