Search code examples
spring-boothibernatejpaspring-data-jpaorm

How to establish a one-way OneToOne relationship?


public class User {

    @Id
    private String user_id;
    
    private String email;
   
    private String password;

    @Getter
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "role_id")
    )
    @JsonManagedReference(value = "users")
    private Set<Role> roles;
}



public class Role {

    @Id
    private String role_id;
   
    private String name;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "roles")
    @JsonBackReference(value = "roles")
    private Set<User> users;
}



public class Student {

    @Id
    @OneToOne
    private User student_id;
    private String name;
    private String email;
    private String phone;
    private String address;
}

Wants to map OneToOne relation with Student and User. But only from the student side, not from the user side. There is no field of Student type in User but User type in Student. Whenever I add a student to the database, the user should be automatically added to the user table.

Is It possible to do?


Solution

  • You can do it with @OneToOne(cascade = CascadeType.ALL) see this similar question or Spring Guru.

    See here for an overview of all CascadeType's.

    public class Student {
    
        @Id
        @OneToOne(cascade = CascadeType.ALL)
        private User student_id;
        private String name;
        private String email;
        private String phone;
        private String address;
    
    }