Skip to content Skip to sidebar Skip to footer

Hibernate: How Do I Map One To One Where B Is A Property Of A?

I have a class A, with property of class B. The SQL table for A does not know anything about B. The SQL table for B contains a foreign key to A. How can I map (in hbm.xml) so that

Solution 1:

I don't especially like this solution, but you can work around the issue by using a couple of wrapper methods. Create a fake getter/setter pair for an unmapped property that gives you the interface you need. Thus:

publicclassPerson{
    private List<Address> addresses;
    // properties, real getters and setterspublic Address getAddress() {
        if (this.addresses == null || this.addresses.isEmpty()) {
            returnnull;
        }
        returnthis.addresses.get(0);
    }

    public void setAddress(Address address) {
        if (this.addresses == null) {
            this.addresses = new ArrayList<Address>();
        }
        this.addresses.clear();
        this.addresses.add(address);
    }
}

Solution 2:

If anyone else is having trouble with a situation like this, I've finally figured it out. Simply map the second table using a

<jointable="Address"><keycolumn="personId"><componentname="address"class="Address"><propertyname="id"column="addressId"type="int" /></component></key></join>

Post a Comment for "Hibernate: How Do I Map One To One Where B Is A Property Of A?"