sheltem
sheltem

Reputation: 3825

JPA OneToMany-Mapping without mapping class for Many-side

In a Spring Boot application using JPA 2.1 and Hibernate, there are two (PostgreSQL) tables of interest:

entity                                external_id
--                                    --
id serial                             id serial
...                                   entity_id int
...                                   external_id int

The relation between entity and external_ids is obviously OneToMany, which I want to use in the JPA mapping as well. A simple way to do this is to create @Entity-mappings for each table and use a @OneToMany-relation:


@Entity
public class Entity {
  @Id
  private Integer id;

  @OneToMany(mappedBy= "entityId")
  private Set<ExternalId> externalIds;
}

@Entity
public class ExternalId {
  @Id
  private Integer id;

  @ManyToOne
  private Integer entityId;

  private Integer externalId;
}

But since the table external_ids just holds a list of numbers for each member of entity, I would like to go without an explicit mapping of the table external_id and immediately map the values of external_id.external_id:


@Entity
public class Entity {
  @Id
  private Integer id;

  @OneToMany(???)
  private Set<Integer> externalIds;
}

Is this possible with JPA 2.1 and if so how?

Upvotes: 4

Views: 2010

Answers (1)

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

You can utilize @ElementCollection for this purpose:

@ElementCollection
@CollectionTable(name = "TableName", joinColumns=@JoinColumn(name = "JoinColumnName"))
private Set<Integer> externalIds;

Upvotes: 5

Related Questions