简体   繁体   中英

Map primary key to non-primary key in another table with different name

I have an object I'll call Foo, I want to map Foo like so:

Foo
-FooId (PK)
-Country
-Name
-Amount

The problem is the database design is poor, so I have two tables with no link table:

Foo (TABLE)
-FooId (PK)
-CountryId (problem child here) - COUNTRY_ID
-Name
-Amount

FooCountry (TABLE)
-CountryId (PK)
-CountryName
-ActualCountryId (I want to tie this to the "Foo" CountryId) - ACTUAL_ID

I'm using an older version of hibernate and Java, so I don't have access to annotations, it all has to be done with plain old XML mapping.

In short, I want to map column "CountryId" to column "ActualCountryId" AND get the full values inside the FooCountry table based on it (ie "Country" as in first example). I am quite sure the "ActualCountryId" column is unique, but it isn't coded that way in the DB, it's just a normal property column.

Can anyone figure this trick out?

Edit: As an added bonus, how would I define the "Country" object within Foo? As a FooCountry?

Edit: This is my mapping inside the Foo XML class area

<key-many-to-one  name="countryId" class="FooCountry" property-ref="actualCountryId" column="COUNTRY_ID" />

I also added the column names for both tables.

If I understand correctly, you want to have a many-to-one association, but with a foreign key to a column which is not the primary key of the target table. This is well described in the Hibernate reference documentation . You just have to use property-ref="propertyNameFromAssociatedClass" in the many-to-one element.

The FooCountry table must be mapped as a regular entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM