I have a following problem with entity mapping in JPA. I have two entities, first one is Lookup and the second is Text which represents translations for entities. Now I need to bound Lookup to the Text but I don't want Text to have reference to Lookup. To make this more complicated, Text does not use its primary key in this relationship but a metacode defined in a TXTHEAD_CODE
column.
Lookup.java
@Entity @Table(name = "DATREG") public class Lookup implements PersistableEntity { @Id @Column(name = "DATREG_META_CODE") private String metaCode; @OneToMany @JoinTable(name="TXT", joinColumns=@JoinColumn(name="DATREG_META_CODE", referencedColumnName="TXTHEAD_CODE"), inverseJoinColumns=@JoinColumn(name="DATREG_META_CODE")) private List<Text> text;
Text.java
@Entity @Table(name = "TXT") public class Text { @Id @Column(name = "TXT_ID") private Long id; @Column(name = "TXTHEAD_CODE") private String code;
So I have tried this (and few other variations) but with no result. I also can't create join table in the DB and I don't want bound Lookup to my Text class. So can anyone please tell me if there is some other way?
As straightforward as it might be in a relational database, when it comes to JPA, the one-to-many database association can be represented either through a @ManyToOne or a @OneToMany association since the OOP association can be either unidirectional or bidirectional.
One-To-One mapping is an association between one persistence object and another one related persistence object. If one persistence object uses other and in back if other is not using the first persistence object then it becomes unidirectional.
The best way to map a @OneToMany association is to rely on the @ManyToOne side to propagate all entity state changes. So, the bidirectional @OneToMany association is the best way to map a one-to-many database relationship when we really need the collection on the parent side of the association.
The direction of a relationship can be either bidirectional or unidirectional. A bidirectional relationship has both an owning side and an inverse side. A unidirectional relationship has only an owning side.
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany @JoinColumn(name="TXTHEAD_CODE") private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany @JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE") private Set<Text> text;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With