3

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> {}
1
  • pls add the endpoint and payload you are trying. Commented Sep 26, 2018 at 6:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.