Spring Rest Data - Foreign key url not mapped to @RequestBody

I am using Spring Rest Data and I have configured my application to use RepositoryRestMvcConfiguration. I have the following 2 objects:

The enterprise has many user relationships.

@Entity
@Table(name="enterprise")
public class Enterprise extends BaseEntity
{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="enterprise_id")
    private Long id;

    @Column(name="enterprise_name")
    private String name;
}

@Entity
@Table(name="user")
public class User extends BaseEntity
{
    @Id
    @Column(name="user_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "owner_enterprise_id", referencedColumnName = "enterprise_id")
    private Enterprise ownerEnterprise;

    @Column(name="username")
    private String userName;

    @Column(name="emailaddress")
    private String emailAddress;

    @Column(name="passwordhash")
    private String password;
}

      

I was able to send a post request to create an enterprise and the next thing I want to do is create a user who has an FK for the enterprise.

Here's my UserController:

@RequestMapping(value="/createUser", method=RequestMethod.POST)
public ResponseEntity<User> register(@RequestBody User user) {

    User newUser = userService.register(user);
    return new ResponseEntity<User>(newUser, HttpStatus.OK);
}

      

When I try to post a message to create a new user:

curl -i -X POST \
-H "Content-Type: application/json" \
-d '{"userName":"johndoe", "emailAddress":"johndoe@gmail.com", "password":"johnpass1", "ownerEnterprise":"http://localhost:8080/enterprises/1"
}' \
http://localhost:8080/createUser

      

I set breakpoints in my controller and saw that the User ownerEnterprise field was null (but the other fields contain correct data). Can someone please help show me what I am missing? I've been trying to find this for hours and with no luck.

I also verified the url is correct:

curl http://localhost:8080/enterprises/1 

    {
      "name" : "MyEnterprise",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/enterprises/1"
        }
      }
    }

      

Thank you for your time!

+3


source to share


2 answers


Your frontend is not Spring-Data-REST, it is a direct Spring MVC request, so the following kind of POST should work for you:

{"userName":"johndoe", "emailAddress":"johndoe@gmail.com", "password":"johnpass1", "ownerEnterprise":{"id":1, "name":"Test Enterprise"}}

      



This is essentially a json representation of your object User

.

If you exposed your user object as @RepositoryRestResource

then your original query should work

+2


source


I faced the same problem. Adding a constructor to the enterprise class should solve it.



public Enterprise(Long id) {
    super();
    this.id = id;

}

      

+1


source







All Articles