包含Map <entity,Entity =“”>字段的正确方法是什么

时间:2019-04-20 13:17:12

标签: java hibernate dictionary jpa cascade

我有一个可以与其他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。这看起来像是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

为了正确定义create index idx on SubscriptionFeed(alertId, name); 映射,您需要组合Map<Entity, Entity>(或@ManyToMany),@OneToMany@JoinTable批注:

@MapJoinColumn

有关更多示例,请参见here