При попытке запуска приложения вылетает org.hibernate.MappingException

Я нашел похожие ошибки в интернете, но советы из ответов либо мало помогли, либо пришлось бы переделать все под связь OneToMany, что мне делать не желательно

Полный текст ошибки
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.spring.config.DataConfig: Invocation of init method failed; nested exception is org.hibernate.MappingException: Foreign key (FKbu6ivurs2s4v3x3yvbj632dwx:user_roles [role_id])) must have same number of columns as the referenced primary key (user_roles [user_id,role_id])

Сущности

User.java

@Entity
@Table(name = "users")
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "name", unique = true)
    private String name;
    @Column(name = "password")
    private String password;
    @Column(name = "email")
    private String email;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<UserRole> roleSet = new HashSet<>();
//getters, setters, constructors

Role.java

@Entity
@Table(name = "user_roles")
@Transient
public class UserRole implements GrantedAuthority {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "role", unique = true, nullable = false)
    private String name;
    @ManyToMany(mappedBy = "roleSet")
    private Set<User> userSet = new HashSet<>();
//getters, setters, constructors

Может кто сталкивался с такой проблемой?

Все остальные классы вроде как реализованы верно, но на всякий случай ссылка на Git-репозиторий


Ответы (2 шт):

Автор решения: Алексей Гумилев

Изменение кода в сущности User с

@ManyToMany(fetch = FetchType.EAGER)

на

    @ManyToMany(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE
    })

исправило данную ошибку (но теперь появилась куча других, эх)

→ Ссылка
Автор решения: azlov

Обратите внимание на ваш класс:

@Entity
@Table(name = "user_roles")
@Transient
public class UserRole implements GrantedAuthority {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "role", unique = true, nullable = false)
    private String name;
    @ManyToMany(mappedBy = "roleSet")
    private Set<User> userSet = new HashSet<>();

А потом эту же таблицу вы описываете как

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles",
           joinColumns = @JoinColumn(name = "user_id"),
           inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<UserRole> roleSet = new HashSet<>();

В первом варианте вы описали user_rolesс полями id и name, а в User.java вы описываете эту таблицу с полями user_id и role_id. На что вам Hibernate вполне объяснимо бросает следующую ошибку: "Foreign key ... user_roles [role_id]..." Он просто не знает на что ссылается role_id.

Решение: вам необходимо описывать в Role.java не таблицу связей user_roles (достаточно того, что вы описали ее в аннотации), а таблицу role. То есть заменить название таблицы @Table(name = "role")или как у вас называется таблица с ролями

→ Ссылка