【问题标题】:Spring rest CRUD saving foreign keySpring Rest CRUD 保存外键
【发布时间】:2019-10-09 20:43:04
【问题描述】:

我需要使用用户 ID 将问题保存到数据库 以下是没有 getter、setter 和构造函数的模型:

@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;
}

这是 QuestionController 中的方法:

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

当我尝试像这样在请求正文中传递数据时:

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

我有一个错误:

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]

我也尝试更改我传递的 userId 键,但没关系,每次它为 null

【问题讨论】:

  • 您可以使用 DTO,然后从 DTO 组合 Question 对象,并通过 id 获取用户。

标签: java spring rest spring-boot spring-data-jpa


【解决方案1】:

你在 POST 上发送这个:

"user_id" : 1

您的 createQuestion 端点会收到:

@Valid @RequestBody Question question

但是您的 Question 类有一个 user,而不是 user_id。你可以这样做:

@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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2021-05-14
    • 2016-08-21
    相关资源
    最近更新 更多