Spring JPA未在MySQL中创建外键,寻求技术帮助
Hey there! As someone new to Spring and Hibernate, it’s totally normal to hit this snag—let’s break down why your foreign keys aren’t generating and fix it step by step.
From the snippet of your ApplicationUser entity you shared, the main red flag is that there are no association annotations telling Hibernate how this entity relates to other tables. Foreign keys are only auto-generated when Hibernate recognizes a relationship between two entities. Here’s what you need to do:
1. Add Association Annotations for Related Entities
If your ApplicationUser is supposed to link to another entity (like a Role, Order, or Address), you need to use Hibernate’s relationship annotations to define that connection. Let’s walk through common scenarios:
Example 1: Many-to-One Relationship (e.g., User belongs to a Role)
Suppose you have a Role entity that your user is associated with. Add this to your ApplicationUser class:
@Entity @Table(name = "application_user") public class ApplicationUser { @Id @GeneratedValue private Integer id; @Column(length=40) private String userName; @Column(length=100) private String password; // ... your other existing fields // Add this association to generate a foreign key @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "role_id", nullable = false) // "role_id" will be the foreign key column in application_user table private Role role; // Don't forget getter and setter for role! }
Make sure your Role entity is properly annotated too:
@Entity @Table(name = "role") public class Role { @Id @GeneratedValue private Integer id; private String roleName; // ... other fields }
Example 2: One-to-Many Relationship (e.g., User has multiple Orders)
If a user can have many orders, add this to ApplicationUser:
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private List<Order> orders = new ArrayList<>();
And in your Order entity, define the inverse side:
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private ApplicationUser user;
2. Verify Hibernate Auto-DDL Configuration
Double-check your application.properties or application.yml to ensure Hibernate is set up to create/update tables:
# For development only—don't use create/create-drop in production! spring.jpa.hibernate.ddl-auto=update
If this is set to none or validate, Hibernate won’t create or modify your schema, including foreign keys.
3. Ensure Consistent Field Types
The foreign key field’s type must match the primary key type of the associated entity. For example, if ApplicationUser’s id is Integer, the foreign key column linking to it (like user_id in Order) must also be Integer—mismatched types will prevent Hibernate from generating the foreign key.
If you still run into issues, feel free to share the code for your other related entities, and we can dig deeper!
内容的提问来源于stack exchange,提问作者Carl Leatherbarrow

