# HQL join for Relational mapping and add extra check

**URL:** <https://discourse.hibernate.org/t/hql-join-for-relational-mapping-and-add-extra-check/9277>\
**Category:** Hibernate ORM\
**Created:** [March 28, 2024, 3:54pm UTC](https://discourse.hibernate.org/t/hql-join-for-relational-mapping-and-add-extra-check/9277 "2024-03-28T15:54:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Varad\_Deshmukh](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/varad_deshmukh/32/2876_2.png) [@Varad\_Deshmukh](https://discourse.hibernate.org/u/Varad_Deshmukh)\
**Post date:** [March 28, 2024, 3:54pm UTC](https://discourse.hibernate.org/t/hql-join-for-relational-mapping-and-add-extra-check/9277/1 "2024-03-28T15:54:05Z")

</div>

```auto
@Entity
@Table(name="casehistory")
public class CaseHistory{

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

    @ManyToOne
	@JoinColumn(name="case_id")
	private Case case;
}

@Entity
@Table(name="cases")
public class Case {

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

    @OneToMany(mappedBy="case_id",cascade = CascadeType.ALL)
	private List<CaseHistory> caseHistories;
}

```

I have this two entities. if I write query like this:

> ```
> StringBuilder queryString=new StringBuilder("SELECT DISTINCT ch.case.id from CaseHistory ch where ch.date>=:fromDate AND ch.date<:toDate and ch.case.id=ch.case.id");
> 
> ```

> ```
> StringBuilder queryString=new StringBuilder("SELECT DISTINCT ch.case.id from CaseHistory ch,Case c where ch.date>=:fromDate AND ch.date<:toDate and c.id=ch.case.id");
> 
> ```

both are equivalent or what?

---

<div class="post-metadata">

**Author:** ![mbladel](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/mbladel/32/2128_2.png) [@mbladel](https://discourse.hibernate.org/u/mbladel)\
**Post date:** [March 28, 2024, 4:18pm UTC](https://discourse.hibernate.org/t/hql-join-for-relational-mapping-and-add-extra-check/9277/2 "2024-03-28T16:18:35Z")

</div>

You don’t need to explicitly add a where condition when using mapped associations: Hibernate will do that for you when translating the HQL query to SQL. You should get the result you’re expecting with:  
`SELECT DISTINCT ch.case.id from CaseHistory ch where ch.date>=:fromDate AND ch.date<:toDate`

In your second query you’re effectively constructing an entity join which is equivalent to the `ch.case` association and, while valid, this is not necessary as I already said.
