0

现在我正在做一个小项目,提交非常简单的工作,我正在努力将它保存到数据库中。考虑这种情况:

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

public class MyJobConfiguration{
     //bunch of configuration fields
}

如您所见,我将这些配置放在单独的类中,这意味着我想添加/更新/删除独立于我的作业对象的配置。

我的目标是首先创建配置,然后在创建作业时为其分配现有配置。

因此,多个作业可以使用相同的配置对象。

我该怎么做?我已经知道如何在数据库中执行此操作,我会将配置的主键连接到 myJob 类中的外键,但在休眠中似乎有所不同。有没有人有例子如何做到这一点?

我发现了这个,因为我认为是它http://www.mkyong.com/hibernate/hibernate-one-to-one-relationship-example-annotation/但似乎不是

4

1 回答 1

1

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.

于 2012-09-18T15:27:42.697 回答