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

Time:12-03

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

CodePudding user response:

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

  • Related