【问题标题】:Why OneToOne relation doesn't works as expected?为什么 OneToOne 关系不能按预期工作?
【发布时间】:2015-08-26 10:38:41
【问题描述】:

我有 2 个实体。用户:

@Table(name = "USERS")
@Entity
public class User {

  @Column(name = "user_id")
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;
  private String name;
  private String email;

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

和身份验证:

@Table(name = "AUTHENTICATIONS")
@Entity
public class Authentication {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int id;
  @Column(name = "login_id")
  private String loginId;//openId login

  @JsonIgnore
  private String password;

  @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinColumn(name = "user_id")
  private User user;
}

我有为新用户提供注册的服务:

@Override
@Transactional
public User createUser(UserRegistrationForm form) {
    Authentication authentication = new Authentication();
    authentication.setPassword(form.getPassword());
    User user = new User();
    user.setAuthentication(authentication);
    user.setEmail(form.getEmail());
    user.setName(form.getLogin());
    authentication.setUser(user);
    return userRepository.save(user);
}

我的问题是方法 userRepository.save() 返回无限嵌套的对象:

{"id":1,"name":"myName","email":"myemail@gmail.com","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"myemail@gmail.com","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"myemail@gmail.com","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"myemail@gmail.com","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"myemail@gmail.com","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"

我做错了什么?帮助了解它应该如何工作。

【问题讨论】:

    标签: java spring hibernate jpa persistence


    【解决方案1】:

    它是返回嵌套对象的 json ......不是你的存储库!

    你正在使用杰克逊? 在一侧添加@JsonManagedReference,在另一侧添加@JsonBackReference

    【讨论】:

    • 没问题 ;) ...那你能接受答案吗?它可能对其他人有用
    【解决方案2】:

    你的问题是:

     user.setAuthentication(authentication);
    ...
        authentication.setUser(user);
    

    userauthentication 之间有一个嵌套引用

    【讨论】:

    • 感谢您的支持。如何在数据库中保存用户并使用他自己的身份验证对象进行分配?
    猜你喜欢
    • 2021-05-30
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多