为什么OneToOne关系不能按预期工作?

时间:2015-08-26 10:38:41

标签: java spring hibernate jpa persistence

我有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":"

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

1 个答案:

答案 0 :(得分:1)

你的问题是:

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

您在userauthentication

之间有一个嵌套引用