Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA MapKey with Nested Attributes

I have 3 elements like this:

public class ItemType {
  @Id
  private Long id = null;
  ...
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "itemTypeVO")
  @MapKey(name = "company.id")
  private Map<Long, ItemTypePurpose> purposeHash = null;
  ...
}


public class ItemTypePurpose {
  @Id
  private Long id = null;
  ...
  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  @JoinColumn(name = "idcompany")
  private Company company = null;
  ...
}

public class Company {
  @Id
  private Long id = null;
  ...
}

My problem is, I want the ID of Company as key of my map inside ItemType .

I can compile and deploy the application without any errors. Can persist ItemType, and everything goes well to DB. But when I get it back, the Map key is "wrong", I don't know what information is being used, but for sure it's not the Company id. Perhaps the ItemTypePurpose's ID.

The Company is being loaded into Map correctly, just the map key is wrong. I've tryied to google, bu can't find anything. Does any way to JPA create my map with this "nested attribute"?

*Sorry about my english, feel free if you understand what I need and can do a better writing in english to edit my question.

like image 504
Rodrigo Leitão Avatar asked Apr 28 '26 01:04

Rodrigo Leitão


1 Answers

This doesn't exactly solves the question, but solve my needs for now.

Since que ID of Company was in table of ItemTypePurpose, I could change the MapKey to:

public class ItemType {
  @Id
  private Long id = null;
  ...
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "itemTypeVO")
  @MapKeyColumn(name = "idcompany", insertable = false, updatable = false)
  private Map<Long, ItemTypePurpose> purposeHash = null;
  ...
}

Instead of @MapKey, I used @MapKeyColumn. The @MapKeyColumn(name = "idcore_company", insertable = false, updatable = false is to turn the "Key Information" ReadOnly and avoid mapping conflict, since the same column is used in ItemTypePurpose to map the Entity.

Not exactly an answer, but "worked around" to solve my needs. This solution does not cover if you want a field as Map Key other than the ID.

like image 184
Rodrigo Leitão Avatar answered Apr 30 '26 15:04

Rodrigo Leitão