London
London

Reputation: 15284

Hibernate annotations relations

Right now I'm working on small project, submitting very simple jobs and I'm working on saving this to the database. Consider this case :

public class Myjob{
   int id;
   int name;
   MyJobConfiguration configuration;
   //etc
}

public class MyJobConfiguration{
     //bunch of configuration fields
}

I have these configurations in separate class as you see, which means I want to add/update/delete configurations independent of my job object.

My goal was to create configuration first and then while creating a job assign an existing configuration to it.

So more than one job can use same configuration object.

How would I do that? I've already got an idea how to do it in the database, I would connect primary key of configuration to foreign key in the myJob class, but it seems different in hibernate. Does anyone have example how to do that ?

I found this one as I thought that is it http://www.mkyong.com/hibernate/hibernate-one-to-one-relationship-example-annotation/ but it seems not

Upvotes: 0

Views: 62

Answers (1)

Jeff
Jeff

Reputation: 3707

You want a one to many relationship, not a one to one as described in the linked article.

You've got a clear idea of how you want the relationship to work, which is nice. Based on what you've said, I would make MyJobConfiguration look like this:

public class MyJobConfiguration {
    @OneToMany(mappedBy = "configuration")
    private List<MyJob> jobs;

    //bunch of configuration fields
}

and MyJob look like this:

public class Myjob{
    int id;
    int name;

    @ManyToOne
    @JoinColumn(name = "configuration_id", nullable = false)
    MyJobConfiguration configuration;
    //etc
}

I might even be inclined to give MyJob a constructor that takes a MyJobConfiguration instance, and make the MyJob() default constructor package-private scoped so that Hibernate can still use it, but callers can't.

Upvotes: 1

Related Questions