Hibernate:从Map字段(Map.key)级联创建对象

uujelgoq  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(142)

我在Class中有一个Map<Object,String>类型的字段。当父类对象保存时,我如何从Map中保存对象?我知道问题出在哪里,但我解决不了。我不能把注解@OneToMane表示cascade = ALL,谈论targets the type 'java.lang.String' which is not an '@Entity' type,我认为这适用于map. value上的注解。请告诉我正确的路。
多谢了。
代码:

@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.

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

ljsrvy3e

ljsrvy3e1#

尝试以下操作

@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;
}

相关问题