Gustav Henriksson
Gustav Henriksson

Reputation: 45

How do i make a one to one relation where tableB holds the foreign key of tableA and where tableA holds a tableB object in spring boot

I have the following entities in a spring boot project:

public class User implements UserDetails {

    @Id
    @GeneratedValue
    private Long id;
    private String email;
    private String password;

    @OneToOne
    private UserInfo info;

}

public class UserInfo {

    @Id
    @GeneratedValue
    private Long id;
    private String firstName;
    private String lastName;
    private String birthDay;
}

And would like to be able to save a new user like this

User user = User.builder()
        .email("[email protected]")
        .password("password")
        .build();
UserInfo userInfo = UserInfo.builder()
        .firstName("foo")
        .lastName("oof")
        .birthDate("ofo")
        .build();
user.setInfo(userInfo);
repository.save(user);

I've only been working directly with SQL before and in my head i would like to have a table structure that looks like follow:

USER TABLE
id
email
password
USER INFO TABLE
user_id
firstname
lastname
birthday

I've tried a few annotations but my boostrapping only works if i use annotations that would make the USER TABLE have a FK to the USER INFO TABLE instead. I'm i missing something here or should i think in another way now when i use spring boot to build my database?

Upvotes: 0

Views: 20

Answers (0)

Related Questions