简体   繁体   中英

Implementing a foreign key relationship in Hibernate

I have a class Problem and then various other classes which extend the base class Solution like BasicSolution , ExpertSolution , many other solution sub classes. The Problem class will be a 'foreign key' for the various solutions classes, although the Problem class doesn't need the solution list.

So I want foreign key of Problem table in various solution tables (one table per solution sub-class). How I can achieve it through Hibernate?

I know that this is not the right DB design from Hibernate's perspective but it's a legacy system and can't be tweaked. I know one-to-many entity association but that will need some Solution list to be present in Problem class (which I don't want).

Can you please suggest some answer to this problem?

You need to map the relation in the Solution base class with @ManyToOne association:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Solution {
...
    private Problem _problem;

    @ManyToOne
    @JoinColumn(name="PROBLEM_ID")
    public Problem getProblem() {
        return _problem;
    }
...
}

All Solution sub classes will have the relation to Problem.

You can also use @OneToOne instead of @ManyToOne, the difference is that @ManyToOne must have the foreign key on this side of the relation.

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