Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: How to select a single item based on a foreign key column that is part of an association mapping?

Hullo, So... I have the following objects:

public class Person {
   // some other getters/setters omitted.
   void setAddress(Address addy) {
       // omitted
   }

   Address getAddress() {
       // omitted
   }
}

public class Address {
   Integer getId() {
      // omitted
   }
}

And, I have the following hibernate mappings:

<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>

    <many-to-one name="address" 
        column="addressId" 
        unique="true"
        not-null="true"/>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
</class>

So, there is a one to one mapping from Person to Address, Person has the foreign key to Address.


What I'm trying to do is fetch a Person object from a given Address ID... but I can't seem to figure out the correct HQL syntax:

public Person getPersonFromAddress(Address address) {

    Query query = this.session.createQuery("select p from Person as p where p.address_id = " + address.getId());

    @SuppressWarnings("unchecked")
    Person p = (Person)query.uniqueResult();

    return p;
}

I know I don't have a mapping from the foreign key column to a property on Person. Everytime I try to add one I get an exception saying I'm using the same column twice? I don't see what would be wrong with that :).

Anyways, what would be the best way to fetch the Person given an Address? Any help would be appreciated.

like image 337
Polaris878 Avatar asked Feb 23 '23 22:02

Polaris878


1 Answers

You should be able to do this

Query query = this.session.createQuery("select p from Person as p where p.address=:address")
            .setParameter("address",address); 
like image 185
Alex Gitelman Avatar answered Apr 08 '23 09:04

Alex Gitelman