我有一个可以与其他MyEntity
关联的实体类MyEntitys
。我想定义MyEntitys之间的关系。所以我结束了像
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;
@Data
@NoArgsConstructor
@RequiredArgsConstructor
@Accessors(chain = true)
@Entity
@Table
public class MyEntity {
@Id
@GeneratedValue
private Long id;
@NonNull
private String name;
private String email;
private String phone;
@NonNull
@OneToOne
private MyEntityType myEntityType;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private Map<String, Address> addresses = new HashMap<>();
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable()
private Map<Relationship, MyEntity> relationships = new HashMap<>();
public MyEntity addAddress(String key, Address address) {
addresses.put(key, address);
return this;
}
public MyEntity addRelationship(Relationship relationship, MyEntity myEntity) {
relationships.put(relationship, myEntity);
return this;
}
}
关系类在哪里
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
@Data
@NoArgsConstructor
@RequiredArgsConstructor
@Entity
@Table
@Accessors(chain = true)
public class Relationship {
@Id
@GeneratedValue
private Long id;
@NonNull
private String name;
@NonNull
private String antonym;
}
有问题的字段是
MyEntity
中的关系字段。在删除MyEntity之前,一切似乎都可行。如果删除的MyEntity没有关系,则一切正常。如果删除的
MyEntity
具有关系,则与之相关的MyEntitys
也将被删除。如果我将
@ManyToMany
批注修改为 @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
然后,不再删除相关的
MyEntitys
。这看起来像是正确的方法吗? 最佳答案
为了正确定义Map<Entity, Entity>
映射,您需要组合@ManyToMany
(或@OneToMany
),@JoinTable
和@MapJoinColumn
批注:
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(...)
@MapKeyJoinColumn(name = "relationship_id")
private Map<Relationship, MyEntity> relationships = new HashMap<>();
有关更多示例,请参见here。