首页 > 解决方案 > 如何在 JPA 中获取外键引用以具有“ON UPDATE CASCADE ON DELETE CASCADE”功能?

问题描述

至少在过去的 6 个小时里,我一直在不停地愚弄这个,我就是不明白问题是什么。我在我的 SpringBoot 项目(用户和项目)中设置了两个类,两个类之间有如下双向关系:

这是我的用户类:

@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

谁能向我解释如何实现这一目标以及为什么我所拥有的不起作用?

标签: javamysqlhibernatespring-bootspring-data-jpa

解决方案


解决

@danblack 告诉我我需要将引擎更改为“Innodb”。我通过添加spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect到我的application.properties文件来做到这一点。

谢谢@danblack!


推荐阅读