Reputation: 251
I have 3 tables: movie, movie_category and category I create entities class
@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;
}
One movie has many film_categories. When i use JpaRepository interface and findAll() for Movie entity hiberante return movieCategories as empty array. I using bidirectional perspective. Using unidirectional is possible return Movie with list categories?
Upvotes: 0
Views: 1301
Reputation: 419
Do not forget to use mappedBy property on ToMany annotations. In your case is necessary because you are using bidirectional association and every bidirectional association has an owner side and an inverse side.
Before it you may have to define the owning side and inverse side. JPA uses the owning side to decide if an association exists between two entities.
The owning side is the one which defines how the association is mapped (using the JoinColumn, JoinTable, etc. annotations). It doesn't have any mappedBy attribute.
The inverse side uses the mappedBy attribute to map which property the attribute is defined in owning side.
Upvotes: 1
Reputation: 272
Try putting the below code in Movie class
@JoinTable(name = "MovieCategory", joinColumns = @JoinColumn(name = "movieId"), inverseJoinColumns = @JoinColumn(name = "categoryId"))
private List movieCategories;
Upvotes: 0