1

I have in Class a field Map<Object, String> type. How can I save Object's from Map when parent Class object save? I understand whats the problem, but cant solve it. I cant place annotation @***ToMany to indicate cascade = ALL, talk targets the type 'java.lang.String' which is not an '@Entity' type, I think thats apply annotation on map.value. Tell me the right way, please.

Thanks a lot.

Code:

@Entity
@Table
public class Profile {
....
    @ElementCollection
    @MapKeyJoinColumn(name="addressId", referencedColumnName = "addressId")
    @Column(name = "description")
    @CollectionTable(name = "ProfileAddress",
            joinColumns = {@JoinColumn(name = "profileId", referencedColumnName = "profileId")})
    private Map<Address, String> addresses; //String it's description for address - "home", "work" etc. I want separate table with parentObjectId, addressId, description. And need that create/delete/update Address object's with Parent object together.

Address is Entity of course.

Error: object references an unsaved transient instance - save the transient instance before flushing

rekki
  • 23
  • 3

2 Answers2

0

Try the following

@Entity
@Table
public class Profile {
....

      @ManyToMany(cascade = {CascadeType.PERSIST,  CascadeType.MERGE})
      @MapKeyJoinColumn(name="addressId", referencedColumnName = "addressId")
      @JoinTable(name = "ProfileAddress",
      joinColumns = {@JoinColumn(name = "profileId", referencedColumnName = "profileId"),  inverseJoinColumns = @JoinColumn(name = "description")))
      private Map<Address, String> addresses;
}
Youans
  • 4,801
  • 1
  • 31
  • 57
  • Thank you for your advice, but an error occurs in application start: Association '...entity.Profile.addresses' targets the type 'java.lang.String' which is not an '@Entity' type. Already I tried ManyToMany, but with one cascade = CascadeType.ALL, the same result. – rekki Jun 30 '23 at 06:49
  • So cascade is not way. It's description from attribute cascade: (Optional) The operations that must be cascaded to the target of the association. When the target collection is a java.util.Map, the cascade element applies to the map value. Defaults to no operations being cascaded. – rekki Jun 30 '23 at 07:06
0

The documentation says

when the map value is a basic type or embeddable class, the ElementCollection annotation is used.

As your map value is the basic type String, I assume @ElementCollection is the annotation you should use.

Medusa
  • 593
  • 2
  • 5
  • 18