使用AccessType.PROPERTY对JPA实体属性调用clear失败

时间:2019-02-19 08:36:00

标签: java hibernate spring-boot jpa spring-data-jpa

我在实体中使用地图。

在设置器中,我清除了地图,然后放置了所有值。我测试了类,值在那里。我保留了该实体:值没有保留,并且存储库的save方法向我返回了一个没有值的实体!!! 我尝试不使用clear ...可以正常工作!

经过一些试验,我发现了一些东西:我尝试使用基本实体和相同的映射。当访问类型为PROPERTY时,它不起作用,但是当我尝试使用访问类型FIELD时,它起作用。

所以问题似乎出在acces类型周围。不幸的是,由于某些工作原因,我无法更改班级层次结构

这是财产和获取者:

@Entity
@Access(AccessType.PROPERTY)
public class MyEntity {

    private Map<MyEnum, Integer> myEnums = new EnumMap<>(MyEnum.class);

    // (...)

    @Override
    @ElementCollection
    @MapKeyColumn(name = "my_enum", columnDefinition = "enum('A', 'B', 'C')")
    @MapKeyEnumerated(EnumType.STRING)
    public Map<MyEnum, Integer> getMyEnums() {
        return myEnums;
    }

    void setMyEnums(Map<MyEnum, Integer> myEnums) {

        // this work
        // this.myEnums= new EnumMap<>(myEnums);

        // this work to (but I can't keep it because the map is not cleared)
        // for (MyEnum myEnum : myEnums.keySet()) this.myEnums.put(myEnum, myEnums.get(myEnum));

        // this doesn't work
        this.myEnums.clear();
        for (MyEnum myEnum : myEnums.keySet()) this.myEnums.put(myEnum, myEnums.get(myEnum));
    }

    // (...)

}

我真的认为这里有个问题。

是否可以使用AccessType.PROPERTY并避免这种行为?我需要使用clear()方法和访问类型PROPERTY。

有关信息,这是一个spring-boot项目,我使用1.5.3.RELEASE和2.0.3.RELEASE重现该问题。

我创建了一个单元测试来重现此问题: https://github.com/Mohicane/jpa-accesstype

1 个答案:

答案 0 :(得分:1)

  

在设置器中,我清除了地图,然后放置了所有值。

那是个坏主意。不要那样做如果您要合并集合,this article解释了如何做到这一点。

  

是否可以使用AccessType.PROPERTY并避免这种行为?

是的,当然有办法。只是不要the DELETE phase is executed after the INSERT phase during the Persistence Context flush以来clear的持久性集合。

  

我需要使用clear()方法和访问类型PROPERTY。

否,您不需要使用clear。您需要执行proper collection merge