jpa@onetomany无法为反向端生成外键

thigvfpy  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(354)

movie类有一个他的会话列表,我想同时保存存储在列表中的movie和他的会话。
这是我的密码

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);
    }

由hibernate生成的sql

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

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

hibernate没有抛出异常,并且电影和会话都成功地被持久化,但是表session中的外键'movie\u id'始终显示为null。
有什么问题吗?当我只使用@onetomany而不使用@manytoone时,同样的测试工作正常,外键添加成功。

ymzxtsji

ymzxtsji1#

在会话实体中,将de movie属性更改为:

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

vsmadaxz2#

结果我漏掉了部分代码。下面是解释原因的链接。jpa@onetomany:外键为空

相关问题