【问题标题】:Method POST for One To One relation一对一关系的方法 POST
【发布时间】:2020-07-12 16:13:16
【问题描述】:

我正在尝试发出 POST 请求以将 UserUserProfile 一起保存,但出现错误。

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

    @OneToOne(fetch = FetchType.LAZY, cascade =  CascadeType.ALL, mappedBy = "user")
    private UserProfile userProfile;
}

@Entity
@Table(name = "user_profile")
public class UserProfile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @JsonIgnore
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;
}

这两种 POST 方法有区别吗?

@RestController
@RequestMapping("/api/user")
public class UserController {
    @PostMapping
    public User save(@RequestBody User user) {
        return userRepository.save(user);
    }

    @PostMapping("/anotherSave")
    public User anotherSave() {
        User user = new User();
        user.setLogin("Login");

        UserProfile userProfile = new UserProfile();
        userProfile.setName("Name");

        user.setUserProfile(userProfile);
        userProfile.setUser(user);

        return userRepository.save(user);
    }
}

第二个完美无误。第一个抛出异常Column 'user_id' cannot be null。下面的 Http 请求是我使用第一个 POST 方法的方式:

POST http://localhost:8080/api/user
Content-Type: application/json

{
  "login": "a",
  "userProfile": {
    "name": "A"
  }
}

我的请求不正确或建立了不正确的关系?

【问题讨论】:

    标签: java rest jpa post one-to-one


    【解决方案1】:

    您的 JSON 请求正文中忽略了 UserProfile.user,所以我想您可以添加类似的内容

    user.getUserProfile().setUser(user);
    

    在您的第一个方法中保存到存储库之前。

    【讨论】:

    • 实际上这行得通。但我假设 save 方法是自己做的?
    • 它没有 - 它只是“按原样”获取并保存实体并在此处失败,因为您的两个数据库表都需要彼此的外键,而您只提供了一个(用户到 UserProfile,因为您将@JsonIgnore 放在另一个上)。从数据库读取时,JPA 将自动解析这两个属性。根据您的特定用例,让一个表具有另一个表的外键可能是更好的选择。
    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多