使用连接表的Hibernate OneToMany

时间:2017-03-09 18:21:48

标签: java hibernate oracle11g orm

我有一个电影实体和一个流派实体。如何插入一个电影,其中包含由其名称给出的流派实体?

例如,类型表

+----+--------+
| id |  name  |
+----+--------+
|  1 | Action |
|  2 |  Drama |
+----+--------+

电影桌

+----+----------+
| id |   name   |
+----+----------+
|  1 | Movie 1  |
|  2 |  Movie 2 |
+----+----------+

加入表

+----+----------+-----------+
| id | movie_id | genre_id  |
+----+----------+-----------+
|  1 |        1 |         1 |
|  2 |        1 |         1 |
|  3 |        1 |         2 |
+----+----------+-----------+

类型实体

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "GENRE")
public class GenreEntity {

    @Id
    @Column(name = "id")
    @GeneratedValue(generator="increment2")
    @GenericGenerator(name="increment2", strategy = "increment") 
    private int id;

    @Column(unique = true,name="name")
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public GenreEntity(){

    }

    public String getName() {
        return name;
    }

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

}

电影实体

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "MOVIE")
public class MovieEntity {
    @Id
    @Column(name = "id")
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment") 
    private int id;

    @Column(name = "RELEASE_DATE")
    private Date releaseDate;

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

    @Column(name = "rating")
    private double rating;

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

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

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

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

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

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(
               name = "CATEGORY", 
               joinColumns = @JoinColumn(name = "movie_id")
             )
    private List<GenreEntity> genre = new ArrayList<>();

    public List<GenreEntity> getGenre() {
        return genre;
    }

    public MovieEntity(){

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Date getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(Date releaseDate) {
        this.releaseDate = releaseDate;
    }

    public String getName() {
        return name;
    }

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

    public double getRating() {
        return rating;
    }

    public void setRating(double rating) {
        this.rating = rating;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getCasting() {
        return casting;
    }

    public void setCasting(String casting) {
        this.casting = casting;
    }

    public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getWriter() {
        return writer;
    }

    public void setWriter(String writer) {
        this.writer = writer;
    }

}

控制器

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import eu.ubis.fiimdb.db.entity.GenreEntity;
import eu.ubis.fiimdb.db.entity.MovieEntity;

@WebServlet("/addmovie")
public class AddMovie extends HttpServlet {
    private String message;

    public void init() throws ServletException
      {
          // Do required initialization
          message = "Hello World";
      }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        // Set response content type
        response.setContentType("text/html");

         SessionFactory factory = new Configuration()
                 .configure("/META-INF/hibernate.cfg.xml")
                 .buildSessionFactory();
         Session session=factory.getCurrentSession();

        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            MovieEntity a = new MovieEntity();
            GenreEntity b = new GenreEntity();
            GenreEntity c = new GenreEntity();
            b.setName("Alex");
            a.setName("teeefasd");
            c.setName("HGFHFG");
            a.getGenre().add(b);
            a.getGenre().add(c);

            session.persist(a);
            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }

    }
}

当我添加电影时,我希望在html和hibernate中有一个select标签,以便在连接表中添加类型,而不是插入到类型表和连接表中。

如何识别这些类型,以便hibernate不再插入它们?

最后,我想转到一个页面,输入一个电影名称并选择适用于该电影并提交的多个类型。

1 个答案:

答案 0 :(得分:1)

首先,该协会是ManyToMany。显然有几部同一类型的电影。

其次,选择框实际上没有理由使用类型的名称作为其选项的值。它应该使用ID,并使用名称作为选项的标签。

因此,归结为以下问题:给定所选流派的ID,如何使用所选流派创建电影。并且anser很简单:使用ID从数据库中获取类型(使用Session.get()Session.load(),或EntityManager.find()EntityManager.getReference())。然后将这些Genre实例存储在创建的Movie的类型列表中。