Mysql
 sql >> Database >  >> RDS >> Mysql

Hibernate Named Query:unisci 3 tabelle

@NamedQuery

Ho creato il seguente @NamedQuery nell'Organization classe di entità.

@NamedQuery(name = "query", query = "SELECT DISTINCT o " +
    "FROM Organization o, User u " +
    "JOIN o.roles oRole " +
    "JOIN u.roles uRole " +
    "WHERE oRole.id = uRole.id AND u.id = :uId")
public class Organization { ...

(Ho usato annotazioni JPA standard, ma il mio provider era Hibernate.)

Test

Questo è il test che ho eseguito.

EntityManager em = ...
TypedQuery<Organization> q = em.createNamedQuery("query", Organization.class);
q.setParameter("uId", 1); // try it with 1L if Hibernate barks about it
for (Organization o : q.getResultList())
  System.out.println(o.name);

Utilizzando le tabelle e i dati di esempio riportati di seguito, questo emette

A
B

Si prega di vedere se funziona per te.

Tabelle

CREATE TABLE `organization` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `organization_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
);

CREATE TABLE `user_has_role` (
  `user_id` int(11) NOT NULL DEFAULT '0',
  `role_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`,`role_id`)
);

ALTER TABLE `role` ADD CONSTRAINT `cst_organization_id` 
  FOREIGN KEY `fk_organiztaion_id` (`organization_id`)
    REFERENCES `organization` (`id`);

(l'ho usato in modo leggermente diverso dal tuo , ma non dovrebbe importare troppo.)

Dati di esempio

`organization`
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
+----+------+

`role`
+----+------+-------------+-----------------+
| id | name | description | organization_id |
+----+------+-------------+-----------------+
|  1 | A    | a           |               1 |
|  2 | B    | b           |               1 |
|  3 | C    | c           |               2 |
+----+------+-------------+-----------------+

`user`
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+

`user_has_role`
+---------+---------+
| user_id | role_id |
+---------+---------+
|       1 |       1 |
|       1 |       2 |
|       1 |       3 |
|       2 |       1 |
|       3 |       1 |
|       3 |       3 |
+---------+---------+