我在 SQL 脚本方面遇到了很多困难。最后,我让他们工作得很好。然后,出于纯粹的兴趣,我删除了表并尝试了 Hibernate 的默认模式创建(基于
@Entity
映射)
spring.jpa.hibernate.ddl-auto=update
-- I'll omit the population part to make it more MRE-ish
-- spring.sql.init.mode=always
-- spring.sql.init.data-locations=classpath:/sql/data.sql
这是我得到的
2023-04-20T06:02:20.227+03:00 WARN 1196 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table users (id bigint not null auto_increment, age tinyint not null, department varchar(255) not null, email varchar(255), enabled tinyint not null, last_name varchar(255) not null, name varchar(255) not null, password varchar(255) not null, salary integer, username varchar(255) not null, primary key (id)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table users (id bigint not null auto_increment, age tinyint not null, department varchar(255) not null, email varchar(255), enabled tinyint not null, last_name varchar(255) not null, name varchar(255) not null, password varchar(255) not null, salary integer, username varchar(255) not null, primary key (id)) engine=InnoDB" via JDBC Statement
at
-- I'll skip a ton of presumably unhelpful lines to make it more MRE-ish
Caused by: java.sql.SQLException: Cannot add foreign key constraint
为什么会这样,在选择依赖 Hibernate 的默认模式创建时如何避免此错误? 您可能已经注意到 Hibernate 的 SQL 语句没有创建 FK(至少没有明确地)。这是我的
@Entity
课程:
@Entity
@Table(name = "users")
@Getter
@Setter
@EqualsAndHashCode
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String name;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(nullable = false)
private String department;
@Column
private int salary;
@Column(nullable = false)
private byte age;
@Column
private String email;
@Column(name = "enabled", nullable = false)
private byte enabledByte;
@ManyToMany
@JoinTable(name = "user_role",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id"),
@JoinColumn(name = "username", referencedColumnName = "username")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id"),
@JoinColumn(name = "role", referencedColumnName = "role")})
@EqualsAndHashCode.Exclude
private Set<Role> authorities;
@Entity
@Table(name = "roles")
@Getter
@Setter
@EqualsAndHashCode
public class Role implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "role", nullable = false, unique = true)
private String authority;
@ManyToMany(mappedBy = "authorities")
@EqualsAndHashCode.Exclude
private Set<User> userList;
我记得我在我的工作台上执行了这个语句(这就是为什么)
set foreign_key_checks=0;
可能相关