Haygo
Haygo

Reputation: 125

Why OneToOne relation doesn't works as expected?

I have 2 entitie. User:

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

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

And I have service which provides registration for new users:

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

And my problem is method userRepository.save() returns infinitely nested objects:

{"id":1,"name":"myName","email":"[email protected]","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"[email protected]","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"[email protected]","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"[email protected]","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"myName","email":"[email protected]","authentication":{"id":1,"loginId":null,"user":{"id":1,"name":"

What am I doing wrong? Help to understand how it should work.

Upvotes: 0

Views: 63

Answers (2)

Pras
Pras

Reputation: 1098

it's json which returns nested objects ... not your repository !

you are using jackson ? add @JsonManagedReference on one side and @JsonBackReference on the other

Upvotes: 2

Fran Montero
Fran Montero

Reputation: 1680

Your problem is:

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

You have a nested reference between user and authentication

Upvotes: 1

Related Questions