0

How should I structure a JSON POST, the controller on my backend, and the POJO classes?

This is for a twitter clone, so a user can have multiple tweets etc

POST

{ "tweet": "Sew one button, doesn't make u a tailor", "user": "Alex" }

Tweet Controller

    public Tweet createTweet(@RequestBody Tweet tweet) {
        return tweetRepository.save(tweet);
    }

Tweet Class

@Table(name = "tweets")
public class Tweet {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(cascade = CascadeType.PERSIST)
    private User user;

    ...

User Class

@Table(name = "custom_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "tweet_id")
    private List<Tweet> tweet = new ArrayList<>();

This is the response I'm getting

{
    "id": 1,
    "user": {
        "id": 2,
        "name": "Alex",
        "tweet": []
    },
    "tweet": "Sew one button, doesn't make u a tailor"
}

edit:

If I do a GET on my users endpoint, this is what I get (there should be associated tweets included)

[
    {
        "id": 2,
        "name": "Alex",
        "tweet": []
    }
]
HahnSolo
  • 125
  • 3
  • 10
  • what do you mean by structure a JSON Post? a post to your endpoint? or a post where? you have already a json format in the example you gave – jpganz18 Jun 21 '19 at 13:56
  • A POST to my endpoint yes, that is what I have so far, but I'm not sure if it's correct. – HahnSolo Jun 21 '19 at 14:05
  • did you try it? it looks fine, as long as it is a valid tweet model, your app should process it same way – jpganz18 Jun 21 '19 at 14:08
  • Why is that tweet not populating in the reponse though? Like nested in the user property? – HahnSolo Jun 21 '19 at 14:11
  • have you debugged and see tweet is not null when you reach tweetRepository.save(tweet);? you can even make a println if you dont have a good ide to debug. is it null? – jpganz18 Jun 21 '19 at 14:17
  • @HahnSolo did the solution I gave work for you? If it did, please consider marking it as best answer for future reference. – Gabriel Robaina Jun 25 '19 at 00:02
  • @GabrielPimenta yes it did. I ended up using JsonBackReference and JsonManagedReference as well to handle the infinite recursion. – HahnSolo Jul 02 '19 at 13:48

1 Answers1

3

Here:

{
    "id": 1,
    "user": {
        "id": 2,
        "name": "Alex",
        "tweet": []
    },
    "tweet": "Sew one button, doesn't make u a tailor"
}

By the looks of it, your Tweet object has a tweet attribute, and your User object has an array that maps every tweet related to that user, that is currently empty on the example.

It looks to me like a problem on your bidirectional mapping between Tweet and User. Consider using the mappedBy property on bidirectional relationships.

Gabriel Robaina
  • 709
  • 9
  • 24