Adil Tokushev
Adil Tokushev

Reputation: 11

Spring rest CRUD saving foreign key

I need to save a question to a database with userid Here is the models without getters, setters and constructor:

@Table(name = "questions")
public class Question {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    @ManyToOne(fetch = FetchType.LAZY, optional = false, targetEntity = User.class)
    @JoinColumn(name = "user_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private User user;
}

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

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

and this is method in QuestionController:

@PostMapping("/questions")
    public Question createQuestion(@Valid @RequestBody Question question) {
        System.out.println("QUESTION " + question.getUser());
        return questionRepository.save(question);
    }

when i try to pass data in request body like this:

{
    "title" : "wtf again?",
    "description" : "asdasdasd asdasdasdasdww asdasdasd",
    "user_id" : 1
}

i have an error:

org.postgresql.util.PSQLException: ERROR: null value in column "user_id" violates not-null constraint
  Detail: Failing row contains (9, asdasdasd asdasdasdasdww asdasdasd, wtf again?, null).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2497) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2233) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149) ~[postgresql-42.2.8.jar:42.2.8]
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124) ~[postgresql-42.2.8.jar:42.2.8]

I also tried to change my passing userId key but it doesn't matter, every time its null

Upvotes: 0

Views: 1220

Answers (1)

Villat
Villat

Reputation: 1475

You're sending this on the POST:

"user_id" : 1

And your createQuestion endpoint receives:

@Valid @RequestBody Question question

But your Question class has an user, not user_id. You could do something like:

@PostMapping("/questions/{userId}")
public Question createQuestion(@PathVariable Long userId, @Valid @RequestBody Question question) {
    Optional<User> user = userRepository.findById(userId);
    if(userId.isPresent()){
        question.setUser(user.get());
        questionRepository.save(question);
        return question;
    }
    return null;
}

Upvotes: 1

Related Questions