1

I have such entities:

Bonus_Request entity:

@Entity
@Table(name = "bonus_request")
public class BonusRequest {

    //some code above...

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "bonusRequest")
    @JsonManagedReference(value = "parameter-bonus_request")
    private Set<BonusRequestParameter> parameters;
}

Bonus_Request_Parameter entity:

@Entity
@Table(name = "bonus_request_parameter")
public class BonusRequestParameter {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Size(max = 30)
    @Column(name = "parameter", nullable = false)
    private String parameter;

    @Size(max = 50)
    @Column(name = "value", nullable = false)
    private String value;

    @JoinColumn(name = "bonus_request_id", nullable = false)
    @ManyToOne(fetch = FetchType.LAZY)
    @JsonBackReference(value = "parameter-bonus_request")
    private BonusRequest bonusRequest;

}

I wonder if it is possible to map the BonusRequestParameter entity as a java.util.Map field in the BonusRequest entity.

For example:

@Entity
@Table(name = "bonus_request")
public class BonusRequest {

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "bonusRequest")
    private Map<String, String> parameters; //String parameter, String value
}

I use:

  1. Spring Data JPA - 2.1.7
  2. PostgreSQL DB - 10.7
  • Entity no. Can you use a map, yes using an `@ElementCollection` and provide mappings for key.value etc. However as it appears that this also has a separate primary key the `@ElementCollection` won't work, because when inserting that won't generate a primary key. So unless you can ditch that column and make the `bonus_request_id` and the `parameter` column the composite key (or unique) it won't work. \ – M. Deinum Oct 25 '19 at 09:21
  • It could also be mapped as private `Map` as detailed here: https://stackoverflow.com/questions/25439813/difference-between-mapkey-mapkeycolumn-and-mapkeyjoincolumn-in-jpa-and-hiber and here https://en.wikibooks.org/wiki/Java_Persistence/Relationships#Map_Key_Columns_(JPA_2.0) – Alan Hay Oct 25 '19 at 17:06

2 Answers2

0

This will work. It loads the map eagerly by default.

@Entity
@Table(name = "bonus_request")
public class BonusRequest {

    ...

    @ElementCollection
    private Map<String, String> parameters; //String parameter, String value
}
Selindek
  • 3,269
  • 1
  • 18
  • 25
0

Resolved with this:

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "bonus_request_parameter",
joinColumns = {@JoinColumn(name = "bonus_request_id", referencedColumnName = "id")})
@MapKeyColumn(name = "parameter")
@Column(name = "value")
private Map<String, String> parameters;

Thank you for help.