简体   繁体   中英

How to use UUID Generator in Spring DATA JPA?

I want to join two models, both are using org.hibernate.id.UUIDGenerator for primary key. But on startup, I get the following error:

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table user_role add constraint FK5scdquo6f12cpstqai86x4biw foreign key (roles_role_id) references role (role_id)" via JDBC Statement

Do you know, what I'm doing wrong?

My code:

User Model:

@Entity
@Table
public class User implements Serializable {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "user_id", columnDefinition = "VARCHAR(255)")
    private String userId;

    @Column(name = "name")
    private String name;

    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "roleId"))
    @ManyToMany
    private List<Role> roles;

    public User(){
        this.roles = new ArrayList<>();
    }
// Getter & Setter
}

Role Model:

@Entity
@Table
public class Role implements Serializable {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "role_id", columnDefinition = "VARCHAR(255)")
    private String roleId;

    @Column(name = "role_name")
    private String name;

    @Column(name = "description")
    private String description;

    @ManyToMany(mappedBy = "roles")
    private List<User> users;

    public Role(){
        this.users = new ArrayList<>();
    }
// Getter & Setter
}

User DAO:

public interface UserDAO extends JpaRepository<User, String > {
}

Role DAO:

public interface RoleDAO extends JpaRepository<Role, String > {
}

Your join column should have a name similar to the column name and not the model variable name. In your case you should use

joinColumns = @JoinColumn(name = "user_id")

and

inverseJoinColumns = @JoinColumn(name = "role_id"))

NOT

joinColumns = @JoinColumn(name = "userId")

and

inverseJoinColumns = @JoinColumn(name = "roleId"))

Also do this for all join columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM