繁体   English   中英

Jpa @onetomany 无法为反向生成外键

[英]Jpa @onetomany can't generate foreign key for the inverse side

电影 class 有他的会话列表,我想同时保留存储在列表中的电影和他的会话。

所以这是我的代码

public class Movie {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "movie_id")
    private int movieId;

    ...

    @OneToMany(mappedBy = "movie",cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Session> sessionList = new ArrayList<>();
}

public class Session {
 @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "session_id")
    private int sessionId;

    ...

    @ManyToOne
    @JoinColumn(name = "movie_id")
    private Movie movie;

}

测试代码

public void testAddMovie(){
        Session session1 = new Session();
        session1.setDay("Monday");


        Movie movie = new Movie();
        movie.setTitle("hello");
        movie.getSessionList().add(session1);

        movieDao.addMovie(movie);
    }

sql 由 hibernate 生成

   insert 
   into
           movies
            (actors, .... ,title) 
        values
            (?, ?, ?, ?, ..., ?, ?, ?, ?)

  insert 
  into
            sessions
            (day, movie_id, time) 
        values
            (?, ?, ?)

Hibernate throws no exception, and both movie and session are successfully persisted but the foreign key 'movie_id' in the table session show always null.

所以有什么问题? 当我只使用没有@manytoone 的@onetomany 时,同样的测试工作正常,外键被成功添加。

在 Session 实体中,将电影属性更改为:

@ManyToOne
@JoinColumn(name = "movie_id", foreignKey = @ForeignKey(name = "fk_session_movie."))
private Movie movie;

事实证明,我错过了部分代码。 这是解释原因的链接。 JPA @OneToMany:外键是 null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM