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

目录:

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

[一]、应用场景

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

[二]、实例演示

1.初始数据

dbunit初始数据如下:

2.单元测试重点是注意Criteria的写法

测试类:OneToManyBidirectionalQBCTest.java

AbstractHibernateBaseTest.java

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

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

Hibernate:

select

this_.ID as ID2_2_,

this_.DESCRIPTION as DESCRIPT2_2_2_,

this_.SEX_TYPE as SEX3_2_2_,

this_.TITLE as TITLE2_2_,

this_.USERNAME as USERNAME2_2_,

c1_.ID as ID3_0_,

c1_.AUTHOR_ID as AUTHOR5_3_0_,

c1_.DETAILS as DETAILS3_0_,

c1_.OTHER as OTHER3_0_,

c1_.TYPE as TYPE3_0_,

author4_.ID as ID2_1_,

author4_.DESCRIPTION as DESCRIPT2_2_1_,

author4_.SEX_TYPE as SEX3_2_1_,

author4_.TITLE as TITLE2_1_,

author4_.USERNAME as USERNAME2_1_

from

DEMO_T_AUTHOR this_

inner join

DEMO_T_CONTACT c1_

on this_.ID=c1_.AUTHOR_ID

left outer join

DEMO_T_AUTHOR author4_

on c1_.AUTHOR_ID=author4_.ID

where

this_.SEX_TYPE=?

and c1_.TYPE=?

order by

this_.USERNAME asc

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

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

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

Hibernate:

select

this_.ID as ID3_1_,

this_.AUTHOR_ID as AUTHOR5_3_1_,

this_.DETAILS as DETAILS3_1_,

this_.OTHER as OTHER3_1_,

this_.TYPE as TYPE3_1_,

a1_.ID as ID2_0_,

a1_.DESCRIPTION as DESCRIPT2_2_0_,

a1_.SEX_TYPE as SEX3_2_0_,

a1_.TITLE as TITLE2_0_,

a1_.USERNAME as USERNAME2_0_

from

DEMO_T_CONTACT this_

inner join

DEMO_T_AUTHOR a1_

on this_.AUTHOR_ID=a1_.ID

where

this_.TYPE=?

and a1_.USERNAME=?

and a1_.TITLE=?

and this_.DETAILS like ?

>>>> 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-qbc/

发表评论?

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=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">