栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Hibernate命名查询-联接3个表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Hibernate命名查询-联接3个表

@NamedQuery

@NamedQuery
Organization
实体类上创建了以下内容。

@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 itfor (Organization o : q.getResultList())  System.out.println(o.name);

使用下面的表和样本数据,此输出

AB

请查看它是否适合您。

桌子

CREATE TABLE `organization` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` varchar(255) COLLATE utf8_unipre_ci DEFAULT NULL,  PRIMARY KEY (`id`));CREATE TABLE `role` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` varchar(255) COLLATE utf8_unipre_ci DEFAULT NULL,  `description` varchar(255) COLLATE utf8_unipre_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 |+---------+---------+


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413576.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号