Hibernate中one-to-many双向关联HQL查询示例

目录:

  1. 应用场景
  2. 实例演示

[一]、应用场景

在实体类中注解配置实现了one-to-many、many-to-one双向关联后(如何配置详见:http://www.micmiu.com/j2ee/hibernate/hibernate-one-to-many-bidirectional-curd/),那么如何运用HQL的方式实现关联查询one 端或者many端的数据?下面我将一一详细讲解,还是以Author 和Contact 作为1:N的实例来演示。

[二]、实例演示

1.初始数据

用dbunit初始数据如下:

2.单元测试(重点是注意HQL的写法)

测试类:OneToManyBidirectionalHQLTest.java,

AbstractHibernateBaseTest.java

运行测试通过,日志如下:

>>>> 测试查询 one 端数据

Hibernate:

select

author0_.ID as ID2_,

author0_.DESCRIPTION as DESCRIPT2_2_,

author0_.SEX_TYPE as SEX3_2_,

author0_.TITLE as TITLE2_,

author0_.USERNAME as USERNAME2_

from

DEMO_T_AUTHOR author0_

inner join

DEMO_T_CONTACT contacts1_

on author0_.ID=contacts1_.AUTHOR_ID

where

author0_.USERNAME=’michael’

and author0_.TITLE=’攻城师’

and contacts1_.TYPE=’blog’

and (

contacts1_.DETAILS like ‘%micmiu.com%’

)

>>>> one-to-many 中 one size:1

Author [id=1, username=michael, title=攻城师, sexType=male, description=IT技术]

>>>> 测试查询 many 端数据

Hibernate:

select

contact0_.ID as ID3_,

contact0_.AUTHOR_ID as AUTHOR5_3_,

contact0_.DETAILS as DETAILS3_,

contact0_.OTHER as OTHER3_,

contact0_.TYPE as TYPE3_

from

DEMO_T_CONTACT contact0_

inner join

DEMO_T_AUTHOR author1_

on contact0_.AUTHOR_ID=author1_.ID

where

author1_.USERNAME=’michael’

and author1_.TITLE=’攻城师’

and contact0_.TYPE=’blog’

and (

contact0_.DETAILS like ‘%micmiu.com%’

)

Hibernate:

select

author0_.ID as ID2_0_,

author0_.DESCRIPTION as DESCRIPT2_2_0_,

author0_.SEX_TYPE as SEX3_2_0_,

author0_.TITLE as TITLE2_0_,

author0_.USERNAME as USERNAME2_0_

from

DEMO_T_AUTHOR author0_

where

author0_.ID=?

>>>> one-to-many 中 many size:1

Contact [id=11, type=blog, details=http://www.micmiu.com/author/michael, other=null]

本文介绍到此结束@Michael Sun.

原创文章,转载请注明: 转载自micmiu – 软件开发+生活点滴[ http://www.micmiu.com/ ]

本文链接地址: http://www.micmiu.com/j2ee/hibernate/hibernate-one-to-many-bidirectional-hql/

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">