【问题标题】:JPA @JoinTable do not create foreign keys in phpmyadminJPA @JoinTable 不在 phpmyadmin 中创建外键
【发布时间】:2018-08-14 08:49:02
【问题描述】:

我是 Hibernate 和 JPA 的新手。
我想在电影之间创建 @ManyToMany 关系 和 Actor 类。

在hibernate.cfg.xml文件中,我设置了如下配置:

<property name="hbm2ddl.auto">update</property>

这里是 Movie 和 Actor 实体的代码快照。

@Entity
public class Movie {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)   
    private Long movie_id;

    @ManyToMany(cascade={CascadeType.PERSIST})
    @JoinTable(
        name="Movie_Actor",
        joinColumns={@JoinColumn(name="movie_id")},
        foreignKey=@ForeignKey(name="fk_movie"),
        inverseForeignKey=@ForeignKey(name="fk_actor"),
        inverseJoinColumns={@JoinColumn(name="actor_id")}
    )
    private Set<Actor> actors = new HashSet<Actor>();

    //default constructor, set & get methods, toString, hashCode, equals
}

@Entity
public class Actor {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)   
    private Long actor_id;

    @ManyToMany(mappedBy="actors")
    private Set<Movie> movies = new HashSet<Movie>();

    //default constructor, set & get methods, toString, hashCode, equals
}

下面我报告了SQL调试:

create table Actor (actor_id bigint not null auto_increment, age integer, name varchar(255) not null, surname varchar(255) not null, primary key (actor_id)) engine=MyISAM
create table Movie (movie_id bigint not null auto_increment, title varchar(255) not null, primary key (movie_id)) engine=MyISAM
create table Movie_Actor (movie_id bigint not null, actor_id bigint not null, primary key (movie_id, actor_id)) engine=MyISAM
alter table Actor drop index uk_name_surname
alter table Actor add constraint uk_name_surname unique (name, surname)
alter table Movie drop index UK_s9ecovryb6e6xo86rh5ddjiyi
alter table Movie add constraint UK_s9ecovryb6e6xo86rh5ddjiyi unique (title)
alter table Movie_Actor add constraint fk_actor foreign key (actor_id) references Actor (actor_id)
alter table Movie_Actor add constraint fk_movie foreign key (movie_id) references Movie (movie_id)

如您所见,似乎外键 "fk_actor" 和 "fk_movie" 已正确创建,但是当我在 phpmyadmin 上看到结果时,这就是我在 Movie_Actor 表结构中的内容:

也就是说,只创建了 "fk_actor" 键。
并查看 Movie_Actor 表数据,这是我所拥有的:

数据不是蓝色,即没有与它们关联的链接(外键)。相反,当我手动添加两个表之间的关系时,我得到了我正在寻找的结果:

如何在不进行手动操作的情况下获得相同的结果?
我做错了什么?我错过了什么?

谢谢

【问题讨论】:

    标签: hibernate jpa phpmyadmin foreign-keys jointable


    【解决方案1】:

    似乎 table engine=MyISAM 没有创建外键约束。我不得不将引擎更改为 INNODB。 在 Java hibernate 中,以下属性将引擎类型更改为 InnoDB

    spring.jpa.database-platform=org.hibernate.dialect.MySQL55Dialect
    #or
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-07
      • 2015-01-18
      • 2016-10-03
      • 2023-03-08
      • 2012-08-16
      • 2017-03-11
      • 1970-01-01
      • 2012-08-08
      相关资源
      最近更新 更多