How to convert collection of entities relation into collection of primitive ids in JPA/Hibernate?

Issue

I have two entities connected with many-to-many relationship. For example:

@Entity
public class Account {
  @Id  
  private Long id;

  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(
        name = "account_games",
        joinColumns = {@JoinColumn(name="account_id")},
        inverseJoinColumns = {@JoinColumn(name="game_id")}
  )
  private Set<Game> games = new HashSet<>();
}

@Entity
public class Game {
  @Id  
  private Long id;

  @ManyToMany(mappedBy = "games", fetch = FetchType.LAZY)
  List<Account> accounts = new ArrayList<>();
}

So, there is a table account_games(account_id, game_id) in mysql describing entities many-to-many relations.

I don’t want to have Game entity anymore. Is there a way to get rid of Game and leave gameId relation only? So, I’d like to have code something like that:

@Entity
public class Account {
  @Id  
  private Long id;

  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(
        name = "account_games",
        joinColumns = {@JoinColumn(name="account_id")},
        inverseJoinColumns = {@JoinColumn(name="game_id")}
  )
  private Set<Long> gameIds = new HashSet<>();
}

without making changes in database.

I’ve tried different configuration on javax.persistance annotations, but none worked

Solution

You can use @ElementCollection and @CollectionTable to achieve that.

@Entity
public class Account {

    @Id
    private Long id;

    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name = "account_games", joinColumns = @JoinColumn(name = "account_id"))
    @Column(name = "game_id", nullable = false)
    private Set<Long> gameIds = new HashSet<>();

}

You may have to change the query on how to filter data using gameId. Element Collection Query

Answered By – Dhaval Gajjar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published