Hibernate 命名查询 - 连接 3 个表

发布于 2024-12-19 18:27:40 字数 2032 浏览 2 评论 0原文

我有 3 个 bean:组织、角色、用户

角色 - 组织关系 - @ManyToOne

角色 - 用户关系 - @ManyToMany

组织:

    @Entity
    @Table(name = "entity_organization")
    public class Organization implements Serializable {

        private static final long serialVersionUID = -646783073824774092L;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE)
        Long id;

        String name;

        @OneToMany(targetEntity = Role.class, mappedBy = "organization")
        List<Role> roleList;

...

角色:

    @Entity
    @Table(name = "entity_role")
    public class Role implements Serializable {

        private static final long serialVersionUID = -8468851370626652688L;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE)
        Long id;

        String name;

        String description;

        @ManyToOne
        Organization organization;

...

用户:

    @Entity
    @Table(name = "entity_user")
    public class User implements Serializable {

        private static final long serialVersionUID = -4353850485035153638L;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE)
        Long id;
        @ManyToMany
        @JoinTable(name = "entity_user_role",
                joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
                inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName =                     "id"))
        List<Role> roleList;

...

所以我需要获取指定用户的所有组织(首先我需要选择所有用户角色和比选择具有此角色的所有组织)

我有一个实现此逻辑的sql语句(例如我选择id = 1的用户):

SELECT * FROM entity_organization AS o 
INNER JOIN entity_role r ON r.organization_id = o.id 
INNER JOIN entity_user_role ur ON ur.role_id=r.id 
WHERE ur.user_id = 1

如何使用hibernate命名查询机制来实现这个? 谢谢!

I have 3 beans: Organization, Role, User

Role - Organization relation - @ManyToOne

Role - User relation - @ManyToMany

Organization :

    @Entity
    @Table(name = "entity_organization")
    public class Organization implements Serializable {

        private static final long serialVersionUID = -646783073824774092L;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE)
        Long id;

        String name;

        @OneToMany(targetEntity = Role.class, mappedBy = "organization")
        List<Role> roleList;

...

Role :

    @Entity
    @Table(name = "entity_role")
    public class Role implements Serializable {

        private static final long serialVersionUID = -8468851370626652688L;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE)
        Long id;

        String name;

        String description;

        @ManyToOne
        Organization organization;

...

User :

    @Entity
    @Table(name = "entity_user")
    public class User implements Serializable {

        private static final long serialVersionUID = -4353850485035153638L;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE)
        Long id;
        @ManyToMany
        @JoinTable(name = "entity_user_role",
                joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
                inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName =                     "id"))
        List<Role> roleList;

...

So I need to get all Organizations for specified User ( first I need to select all user roles and than select all organizations that have this roles)

I have an sql statement that realizes this logic ( for e.g. I choose user with id = 1):

SELECT * FROM entity_organization AS o 
INNER JOIN entity_role r ON r.organization_id = o.id 
INNER JOIN entity_user_role ur ON ur.role_id=r.id 
WHERE ur.user_id = 1

How can I implement this, using hibernate named query mechanism?
Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

信仰 2024-12-26 18:27:40

@NamedQuery

我在 Organization 实体类上创建了以下 @NamedQuery

@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 { ...

(我使用标准 JPA 注释,但我的提供程序是 Hibernate。)

测试

这是我运行的测试。

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);

使用下面的表格和示例数据,此输出

A
B

请查看它是否适合您。

表格

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`);

(我使用的与你的有点不同,但应该不会太重要。)

示例数据

`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 |
+---------+---------+

@NamedQuery

I've created the following @NamedQuery on the Organization entity class.

@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 { ...

(I used standard JPA annotations, but my provider was Hibernate.)

Test

This is the test I ran.

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);

Using the tables and sample data below, this outputs

A
B

Please see if it works for you.

Tables

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`);

(I've used a bit different from yours, but it shouldn't matter too much.)

Sample data

`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 |
+---------+---------+
回梦 2024-12-26 18:27:40

尝试如下 HQL:

select ur.roleList.organization from User ur where ur.id = 1 

它将为您提供 List

Try the HQL as below:

select ur.roleList.organization from User ur where ur.id = 1 

It will give you the List<Organization>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文