java - 如何在 JPA 中获取外键引用以具有“ON UPDATE CASCADE ON DELETE CASCADE”功能?
问题描述
至少在过去的 6 个小时里,我一直在不停地愚弄这个,我就是不明白问题是什么。我在我的 SpringBoot 项目(用户和项目)中设置了两个类,两个类之间有如下双向关系:
- 从用户到项目的@OneToMany 关系(一个用户可以拥有多个项目)
- 从项目到用户的@ManyToOne 关系(每个项目只有一个用户)
这是我的用户类:
@Data
@Entity
@AllArgsConstructor
@Table(name="users")
public class User implements Serializable {
@Id
private @NotNull String id;
private @NotNull String username;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.owner", cascade = CascadeType.ALL)
private List<Item> ownedItems;
...
}
这是我的 Item 类(它使用复合主键):
@Data
@Entity
@AllArgsConstructor
@Table(name="items")
public class Item implements Serializable {
@Data
@Embeddable
public static class PrimaryKey implements Serializable {
private @NotNull String id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(
name="user_id",
referencedColumnName = "id",
foreignKey = @ForeignKey(name = "FK_Item_UserID"),
nullable = false, // I have tried using these
updatable = false, // and excluding these and
insertable = false // that changes nothing
)
private @NotNull User owner;
}
@EmbeddedId
private @NotNull PrimaryKey pk;
private @NotNull String name, item_condition, categories;
private @NotNull LocalDateTime postDate;
}
问题是由 Hibernate 创建的表(由 SQL 查询“SHOW CREATE TABLE items”返回是这样的:
CREATE TABLE `items` (
`id` varchar(255) NOT NULL,
`categories` varchar(255) NOT NULL,
`item_condition` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`post_date` datetime NOT NULL,
`user_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`,`user_id`),
KEY `FK_Item_UserID` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
请注意,外键引用只是一个 KEY 而不是 FOREIGN KEY。下一个问题是它在更新或删除时没有做任何事情,这是一个大问题。我希望该表的外键如下所示:
FOREIGN KEY ('user_id') REFERENCES Users('id') ON UPDATE CASCADE ON DELETE CASCADE
谁能向我解释如何实现这一目标以及为什么我所拥有的不起作用?
解决方案
解决
@danblack 告诉我我需要将引擎更改为“Innodb”。我通过添加spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect
到我的application.properties
文件来做到这一点。
谢谢@danblack!
推荐阅读
- excel - Excel 会计在草稿帐户上的存款和取款表
- sql - CakePHP 2.10 中的 SQL 子表达式
- python - Pandas:.tolist() 提供浮点数
- inheritance - 实现对另一个接口的依赖
- python - 如何检查异常中的消息
- reactjs - 如何解决自定义组件的 Material UI 中的“muiName”?
- javascript - 如何在asp.net c#中使用jquery验证更改多选板颜色
- javascript - 您将如何访问或覆盖派生类声明中基类的私有属性?
- node.js - 如何使用 node js 和 PostgreSQL 实现 Session 认证
- c++ - 如何将 COM 指针传递给一组等待后台线程中的每个线程