在休眠中,如何在查询多个表时从一个表中选择结果

时间:2012-02-20 01:29:52

标签: hibernate join inner-join

我想创建一个Hibernate查询,它将返回一个电影列表,詹姆斯邦德是由一位现已超过60岁的演员扮演的。 (别担心这个例子的愚蠢)

我尝试过很多与createQuery的组合,但无法在连接上设置条件。

另外,另一个目标是我希望查询返回List< Movie>而不是List< String>或列表< Whatever>。

更具体地说,我想运行的SQL如下:

SELECT m.* FROM movies m
INNER JOIN movie_actors ma
    ON (ma.movie_id = m.id AND ma.role = 'James Bond')
INNER JOIN actors a
    ON (a.id = ma.actor_id AND a.age > 60)

为此,我假设这个表模式:

CREATE TABLE movies(
id            INTEGER          NOT NULL,
name          NVARCHAR2(100)    NOT NULL,

CONSTRAINT pk_movies PRIMARY KEY (id),
);

CREATE TABLE movie_actors (
movie_id  INTEGER       NOT NULL,
actor_id  INTEGER       NOT NULL,
role      NVARCHAR2(200) NOT NULL,

CONSTRAINT fk_movies_actors_movie_id  FOREIGN KEY (movie_id)  REFERENCES movies,
CONSTRAINT fk_movies_actors_actor_id  FOREIGN KEY (actor_id) REFERENCES actors
);

CREATE TABLE actors (
  id         INTEGER         NOT NULL, 
  firstname  NVARCHAR2(50)   NOT NULL, 
  lastname   NVARCHAR2(50)   NOT NULL,
  age        INTEGER       NOT NULL,

  CONSTRAINT pk_actors  PRIMARY KEY (id)
);

2 个答案:

答案 0 :(得分:1)

如果不添加关系,HQL查询可以如下所示。我们需要使用属性将Java Bean名称和列名替换为表名。还要向Movie类添加构造函数,以设置idname,以List<Movie>而不是List<Object[]>为结果。

SELECT new Movie (m.id, m.name) FROM movies m
INNER JOIN MovieActors ma
    ON (ma.movieId = m.id AND ma.role = 'James Bond')
INNER JOIN actors a
    ON (a.id = ma.actorId AND a.age > 60)

阅读API here或一些示例here以获取更多信息。

答案 1 :(得分:1)

两个表

1)CivilDashboard

2)ProjectSubcompChild

from CivilDashboard cd1 
where cd1.civilDbPkid in ( select cd.civilDbPkid as civilDbPkid 
                           from ProjectSubcompChild sc, CivilDashboard cd 
                           where sc.subcompChildPkid = cd.projectSuncompChildPkid)