0

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?

1
  • Add mappedBy = "movie" in the relationship in Movie.java @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "movie") private List<MovieCategory> movieCategories; Commented May 31, 2018 at 16:47

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try putting the below code in Movie class

@JoinTable(name = "MovieCategory", joinColumns = @JoinColumn(name = "movieId"), inverseJoinColumns = @JoinColumn(name = "categoryId"))

private List movieCategories;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.