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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With