Sagar Varpe
Sagar Varpe

Reputation: 3599

Query handling for Null reference in Hibernate

I Am using hibernate and i have a Entity like

@Entity
@Table(name = "MyEntity")
Class MyEntity {
        @Id
    @GeneratedValue
    private long id;

    @Column(name = "NAME")
    private String name;

    //some more attributes here 

        @OneToOne
    @JoinColumn(name = "PARENT_ID")
        MyEntity parent;

}

I have one record in database

id   |  name | parent_id 

125 |   n1  |   null

and when i am trying to get this record with hibernate Query

Select e.id,e.name,e.parent.name from MyEntity e where e.id =125

this query is returning me zero records.because the parent is null here, so is there any way to handle this kind of situation. thanks in advc.

Upvotes: 0

Views: 1210

Answers (2)

Sebastien Lorber
Sebastien Lorber

Reputation: 92140

Like others said, this leads to an innerjoin...

You may add the following properties to your hibernate:

hibernate.show_sql=true
hibernate.format_sql=true

This way you would be able to know what hibernate is trying to do and notice by yourself such problems...

If the SQL generated doesn't give you the expected result, then you have a problem in your hibernate request. In this case it's not hard to understand that you must tell hibernate to do a left outer join instead of an inner join.

If one day you need method parameters, look at this: Hibernate show real SQL

You could also have used the Criteria api which is pretty simple et powerful to use and maintain when there are no joins in every directions.

Upvotes: -1

axtavt
axtavt

Reputation: 242696

In your case Hibernate implicitly uses inner join that doesn't return anything when one of the sides is null.

You can instruct Hibernate to use left outer join instead as follows:

select e.id, e.name, p.name from MyEntity e left join e.parent p where e.id = 125

Upvotes: 5

Related Questions