Pavlo K.
Pavlo K.

Reputation: 371

JPA/Hibernate Unidirectional OneToMany as 'mappedBy'

I recently found such mapping in our repo:

@Entity
...
public class Foo{
     ...
     @OneToMany(mappedBy = "someField", cascade = CascadeType.ALL, orphanRemoval = true)
     public Set<Bar> bars;
     ...
}

@Entity
@IdClass(Bar.Key.class)
...
public class Bar{
     @Id
     public long someField;
     @Id
     public long anotherField;
     ...
     static class Key implements Serializable {
        public long someField;
        public long anotherField;
     }
}

There are no foreign keys in both tables. I was surprised that there is no @ManyToOne field in the Bar class and @OneToMany is annotated without @JoinColumn as mappedBy. Anyway it works perfectly: without redundant updates - like it's a bidirectional mapping. I'm not an expert in JPA/Hibernate and I've never seen such mapping in tutorials/guides/docs. I tried to google such mapping but I didn't find any explanation. Is it OK to map entities like this? Thanks!

Upvotes: 0

Views: 2161

Answers (1)

Khalid Shah
Khalid Shah

Reputation: 3232

Bidirectional one-to-many and both many-to-one association mappings are fine. But you should avoid unidirectional one-to-many associations in your domain model. Otherwise, Hibernate might create unexpected tables and execute more SQL statements than you expected.

The definition of an unidirectional one-to-many association doesn’t seem to be an issue. You just need an attribute that maps the association and a @OneToMany relationship.

Reference see ref

Upvotes: 1

Related Questions