Question

I am new to hibernate, I am trying to learn it and I have run into a problem trying to make one to many relationship's work. I have tried several examples but none seem to be working.

Can someone have a look at the below code and tell me where I have gone wrong. I have tried many different tutorials but it always doesn't work, so I must be missing something.

There are two classes: MovieDb and Genre. For each movie there should be many Genre's.

I believe I have included all the files and information needed, if not let me know.

Thanks for the help.

MovieDb.java

@Entity
@Table(name = "movies")
public class MovieDb extends IdElement {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @JsonProperty("id")
    @Column(name = "movieId")
    private int movieId;

    @JsonProperty("title")
    @Column(name = "title")
    private String title;

    @JsonProperty("genres")
    @OneToMany
    private List<Genre> genres;

    public int getMovieId() { return movieId; }
    public String getTitle() { return title; }
    public List<Genre> getGenres() { return genres; }

    public void setMovieId(int movieId) { this.movieId = movieId; }
    public void setTitle(String title) { this.title = title; }
    public void setGenres(List<Genre> genres) { this.genres = genres; }
}

Genre.java

@JsonRootName("genre")
@Entity
@Table(name = "moviesGenre")
public class Genre implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private int id;

    @Column(name = "movieId")
    private int movieId;

    @JsonProperty("name")
    @Column(name = "name")
    private String name;

    public int getMovieId() { return movieId; }
    public String getName() { return name; }

    public void setMovieId(int movieId) { this.movieId = movieId; }
    public void setName(String name) { this.name = name; }
}

Main.java

public MovieDb getMovie(int movieId) {
    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = s.beginTransaction();
    MovieDb movie = null;
    try {
        String hql = "FROM MovieDb E WHERE E.movieId = " + movieId;
        Query query = s.createQuery(hql);
        List movies = query.list();
        movie = (MovieDb)movies.get(0); 
        tx.commit();
    }catch (HibernateException ex) {
        if (tx != null) 
            tx.rollback();
    }finally {
        s.close(); 
    }
    return movie;
}

public void saveMovie(MovieDb movie) {
    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = s.beginTransaction();
    try {
        s.save(movie);
        s.flush();
        tx.commit();
    } catch (HibernateException ex) {
        if (tx != null) 
            tx.rollback();
    } finally {
        s.close(); 
    }
}

My database is setup like this:

movies

id          int           (primary)
movieId     int
title       varchar

moviesGenre

id          int           (primary)
movieId     int 
name        varchar

My Hibernate.cfg.xml file showing mapping is below:

Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    ...
    ...
    ...
    <mapping class="com.medialibrary.api.model.MovieDb"/>
    <mapping class="com.medialibrary.api.model.Genre"/>
  </session-factory>
</hibernate-configuration>
Was it helpful?

Solution

on the MovieDb class side

@OneToMany(mappedBy="movie", cascade = CascadeType.ALL)
private List<Genre> genres;

and in Genre

@ManyToOne
@JoinColumn(name="movieId")
    private MovieDb movie;

Bugs in the code:

when you are saving parent entity then them children are not persisted as long as you do not use CascadeType.PERSIST or CascadeType.ALL (for all the operation types)

you are trying to do a bidirectional relation so you have to specify the owner mappedBy="movie" will do this job - it says that a moveId will be written on the Genre side

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top