JPA @JoinTable不在phpmyadmin中创建外键

时间:2018-03-06 13:17:43

标签: hibernate jpa phpmyadmin foreign-keys jointable

我是Hibernate和JPA的新手 我想在Movie之间创建一个 @ManyToMany 关系 和演员班。

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

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

这是来自电影演员实体的代码快照。

@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)

正如您所看到的,似乎正确创建了外键&#34; fk_actor&#34; &#34; fk_movie&#34; ,但随后当我在 phpmyadmin 上看到结果时,这就是我在Movie_Actor表结构中的内容:

Movie_Actor table structure

即只创建了&#34; fk_actor&#34; 键。
看看Movie_Actor表数据,这里有我所拥有的:

Movie_Actor table data

数据非蓝色,即没有与之关联的链接(外键)。相反,我手动添加两个表之间的关系,我有我想要的结果:

Movie_Actor table data after creating manual relationship

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

由于

1 个答案:

答案 0 :(得分:0)

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

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