Search code examples
javaspring-boothibernatejpaone-to-one

JPA - Hibernate - OneToOne


I have a OneToOne relation between tables User and Profile defined like so:

@Entity
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name="users", uniqueConstraints = { 
        @UniqueConstraint(columnNames = "username"),
        @UniqueConstraint(columnNames = "email")
    }
)
public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idUser;
    private String username;
    private String email;
    private String password;
    
    @OneToOne(cascade=CascadeType.ALL, orphanRemoval=true)  
    @JoinColumn(name="id_profile", referencedColumnName="idProfile")
    private Profile profile;
    
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Role> roles = new LinkedHashSet<Role>();

}
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name="profile",
    uniqueConstraints = @UniqueConstraint(columnNames = "discordId")
)
public class Profile implements Serializable {
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idProfile;
    private Date birthday;
    private String discordId;
    private String description; 
    @ElementCollection(fetch=FetchType.EAGER)
    private Set<String> spokenLanguages = new LinkedHashSet<String>();

    @OneToMany(fetch=FetchType.EAGER)
    private Set<ProfileGame> profileGames = new LinkedHashSet<>();
    
    @OneToOne(mappedBy="profile")
    private User user;
    
    @ManyToOne
    private TimeSlot timeSlot;
    
}

Then I run a test to make some fixtures in my database:

Profile profile = this.profileRepository.save(Profile.builder()
                    .birthday(new Date())
                    .discordId("discord-" + i)
                    .description("Description de user-" + i)
                    .spokenLanguages(spokenLanguages)
                    .timeSlot(timeSlot)
                    .build());
            user.setProfile(profile);
            System.err.println(user);

Everything works fine here, System.err.println(user) returns correct values.

The issue comes from the database, which doesn't "apply" the id_profile in my User table:

enter image description here

What did I miss?


Solution

  • Try to do something like this:

    Profile profile = Profile.builder()
       .birthday(new Date())
       .discordId("discord-" + i)
       .description("Description de user-" + i)
       .spokenLanguages(spokenLanguages)
       .timeSlot(timeSlot)
       .user(user)
       .build();
    user.setProfile(profile);
    profile = this.profileRepository.save(profile);
    

    You use a bidirectional @OneToOne association, so you should make sure both sides are in-sync at all times.

    Also, as you need to propagate persistent state to the user, you should add cascade = CascadeType.ALL to the Profile.user like below:

    @Entity
    public class Profile implements Serializable {
        
        // ...
    
        @OneToOne(mappedBy="profile", cascade=CascadeType.ALL)
        private User user;
        
    }