我有 3 个表:movie、movie_category 和category 我创建实体类
@Entity
@Table(name = "category")
@Data
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, unique = true)
private Integer categoryId;
private String name;
}
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, unique = true)
private Integer movieId;
........
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<MovieCategory> movieCategories;
}
@Entity
@Table(name="movie_category")
@Data
public class MovieCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, unique = true)
private Integer movieCategoryId;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "movieId", referencedColumnName = "movieId")
private Movie movie;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "categoryId", referencedColumnName = "categoryId")
private Category category;
}
一部电影有多个 film_categories。当我使用 JpaRepository 接口(interface)和 findAll() 作为 Movie 实体时,hiberante 返回 movieCategories 作为空数组。我使用双向视角。使用单向可以返回带有列表类别的电影吗?
最佳答案
不要忘记在 ToMany 注释上使用mappedBy 属性。在您的情况下这是必要的,因为您正在使用双向关联,并且每个双向关联都有一个所有者方和一个反向方。
在此之前,您可能必须定义拥有方和反方。 JPA 使用拥有方来决定两个实体之间是否存在关联。
拥有方定义关联的映射方式(使用 JoinColumn、JoinTable 等注释)。它没有任何mappedBy 属性。
反方使用mappedBy属性来映射该属性是在拥有方定义的属性。
关于java - Hibernate返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50628822/