hibernate foreign key mapping many-to-one

I have been working on it for quite a while, but still can't figure out what's wrong with my code. Each Service has multiple profiles, but each profile only has one Service.

Service
{
Long service_id; // primary key
... getter/setter
}

Profile
{
Long profile_id; // primary key
Long service_id; // foreign key
... getter and setter
}

in Profile.hbm.xml. I add

< many-to-one name="service_id" class="com.mot.diva.dto.Service" column="SERVICE_ID" cascade="save-update">
< /many-to-one>

Is it the correct way to map it?

Answers


Each Service has multiple profiles, but each profile only has one Service.

Then design your object model accordingly. When using an ORM tool, you need to think object (entities) and relations between entities, not ids. The ORM will take care of PK, FK, joins, etc. So your code should be something like this:

public class Service implements Serializable {
    private Long service_id; // primary key
    private Set<Profile> profiles = new HashSet<Profile>();

    // ... getter/setter
}

public class Profile implements Serializable {
    private Long profile_id; // primary key
    private Service service;

    // ... getter and setter
}

And the Profile.hbm.xml mapping file:

....
<many-to-one name="service" 
             class="com.mot.diva.dto.Service"
             column="SERVICE_ID"
             cascade="save-update">
</many-to-one>
...

And in Service.hbm.xml (because your association seems to be bi-directional):

...
<set name="profiles" inverse="true">
    <key column="PROFILE_ID" not-null="true"/>
    <one-to-many class="com.mot.diva.dto.Profile"/>
</set>
...

Need Your Help

How do I stub/mock a call to the command line with rspec?

ruby command-line rspec

I'm trying to test output from a command line tool. How do I 'fake' a command line call with rspec? Doing the following doesn't work:

Database mongoDB or mysql

mysql json mongodb

I'm creating a search engine for deals, disscounts and coupons. First with my engine I collect deals from some sites and write that deals into database. So an records have a: