Не удается сохранить внешний ключ с помощью Hibernate @JoinColumn и mappedBy - PullRequest
0 голосов
/ 18 марта 2020

У меня есть метод в классе обслуживания, который берет DTOProfile и пользователя от контроллера. Когда он сохраняет навыки профиля, он только записывает свой идентификатор и имя в базу данных, внешний ключ всегда равен нулю. Вот мои сущности и услуги

Профиль:

@Getter
@Setter
@EqualsAndHashCode(of = {"id"})
@Entity
@Table(name = "profiles")
@ToString
public class Profile {
    @Id
    private Long id;

    private String profilePicture;

    private String skype;

    private String phone;

    private String telegram;

    private String jobTitle;

    @OneToMany(mappedBy = "profile", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Skill> skills;

    private String country;

    @OneToOne
    private User user;

    @OneToMany(cascade = CascadeType.ALL,
            fetch = FetchType.EAGER, mappedBy = "sourceProfile")
    private List<Rating> ratings = new ArrayList<>();


    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_subscriptions",
            joinColumns = @JoinColumn(name = "source_profile_id"),
            inverseJoinColumns = @JoinColumn(name = "destination_profile_id")
    )
    private Set<Profile> subscriptions;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_subscriptions",
            joinColumns = @JoinColumn(name = "destination_profile_id"),
            inverseJoinColumns = @JoinColumn(name = "source_profile_id")
    )
    private Set<Profile> subscribers;

    public Profile() {
    }

    public Profile(User user) {
        this.id = user.getId();
        this.user = user;
    }

}

Умение:

@Entity
@Setter
@Getter
@EqualsAndHashCode
@Table(name = "skills")
public class Skill {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "profile_id", nullable = false)
    private Profile profile;
}

Способ обслуживания:

public Boolean updateProfile(DTOProfile dtoProfile, User currentUser) {

        if (currentUser != null) {
            Profile profileFromDB = profileRepository.findProfileById(currentUser.getId());
            if (profileFromDB != null) {
                boolean isProfileUpdated = false;
                if (dtoProfile.getSkype() != null) {
                    profileFromDB.setSkype(dtoProfile.getSkype());
                    isProfileUpdated = true;
                }
                if (dtoProfile.getPhone() != null) {
                    profileFromDB.setPhone(dtoProfile.getPhone());
                    isProfileUpdated = true;
                }
                if (dtoProfile.getTelegram() != null) {
                    profileFromDB.setTelegram(dtoProfile.getTelegram());
                    isProfileUpdated = true;
                }
                if (dtoProfile.getSkills() != null) {
                    profileFromDB.setSkills(dtoProfile.getSkills());
                    isProfileUpdated = true;
                }
                if (dtoProfile.getCountry() != null) {
                    profileFromDB.setCountry(dtoProfile.getCountry());
                    isProfileUpdated = true;
                }
                if (dtoProfile.getJobTitle() != null) {
                    profileFromDB.setJobTitle(dtoProfile.getJobTitle());
                    isProfileUpdated = true;
                }
                if (isProfileUpdated) {
                    profileRepository.save(profileFromDB);
                    return true;
                }
            } else return false;
        } else return false;
        return false;
    }

DTOProfile указан в json. Что-то вроде

{
    "jobTitle": "director",
    "country": "us",
    "skills": [{"name": "skill0"}, {"name": "skill1"}, {"name": "skill2"}]
}

Пользователь является текущим пользователем в системе

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...