Issue
I'm using JPA annotation with Hibernate and I don't really know how to manage an association table.
The entity relationship
Here is my database schema as entity-relationship (ER) diagram:
COUNTRY COUNTRY_MOVIE
|---------|* *|---------------| | MOVIE |
| COU_ID |<---->| COUNTRY_ID |* *|---------|
| LABEL | | MOVIE_ID |<---->| MO_ID |
|---------| |---------------| | LABEL |
|---------|
The table COUNTRY_MOVIE
is an association table between COUNTRY
and MOVIE
with many-to-many associations (symbolized by the arrow-lines above where many-to-many expressed by * *
) .
The entities modeled in code with JPA
In my JPA object I didn't create a CountryMovie.java
class.
Country
But I use @JoinTable
in Country.java
as in the following code:
//Package, Import...
@Entity
@Table(name="COUNTRY")
public class Country implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="COU_ID")
private Integer couID;
@Column(name="LABEL")
private String label;
//bi-directional many-to-many association to TFilmFil
@ManyToMany
@JoinTable(
name="COUNTRY_MOVIE"
, joinColumns={
@JoinColumn(name="COU_ID")
}
, inverseJoinColumns={
@JoinColumn(name="MO_ID")
}
)
private List<Movie> movies;
public Country() {
super();
}
// Other constructor, Getter & Setter, and "toString" method...
}
Movie
And in Movie.java
I use only a @ManyToMany
annotation :
//Package, Import...
@Entity
@Table(name="MOVIE")
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="MO_ID")
private Integer moId;
@Column(name="LABEL")
private String label;
//bi-directional many-to-many association to TrPaysPay
@ManyToMany(mappedBy="movies")
private List<Country> countries;
public Film() {
super();
}
// Other constructor, Getter & Setter, and "toString" method...
}
Issue 1: LazyInitializationException
I don't know if it's the best way to manage this kind of association table even if it looks OK.
But when I try to get all the countries of a movie I obtain a LazyInitializationException
from Hibernate.
Issue 2: After I tried FetchType.EAGER
So I tried to add a fetch EAGER to each many-to-many annotation:
In Country
:
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
In Movie
:
@ManyToMany(mappedBy="movies",fetch=FetchType.EAGER)
Then I obtain this :
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
Questions
- Do I have to create another java class to map
COUNTRY_MOVIE
? - Or is there a way to fix this problem by using the same java class as now?
Solution
Your mapping is alright (you don't need a third class). You also don't need to make it eager fetch. The problem is with the querying code. You should make sure that the session is still open when you access the collection.
Update the question with your query code and I can tell you how to fix it.
Answered By - gkamal